ionic入门之多组件开发模式

xiaoxiao2021-02-28  53

在实战中建议是用多组件开发模式, 高耦合低内聚。 文件名和组件名遵循风格指南中的标准方式。 组件的类名应该是大驼峰形式,并且以Component结尾。 因此英雄详情组件的类名是HeroDetailComponent。 组件的文件名应该是小写中线形式,每个单词之间用中线分隔,并且以.component.ts结尾。 因此HeroDetailComponent类应该放在hero-detail.component.ts文件中。

目录结构

hero.component.html

<div padding> <h1>{{title}}</h1> <ul class="heroes"> <li *ngFor="let hero of heroes" [class.selected]="hero === selectedHero" (click)="onSelect(hero)"> <span class="badge">{{hero.id}}</span> {{hero.name}} </li> </ul> <hero-detail [hero]="selectedHero"></hero-detail> </div>

hero.component.scss

my-app { .selected { background-color: #CFD8DC !important; color: white; } .heroes { margin: 0 0 2em 0; list-style-type: none; padding: 0; width: 15em; } .heroes li { cursor: pointer; position: relative; left: 0; background-color: #EEE; margin: 5px 5px 5px 5px; height: 25px; border-radius: 4px; } .heroes li.selected:hover { background-color: #BBD8DC !important; color: white; } .heroes li:hover { color: #607D8B; background-color: #DDD; left: .1em; } .heroes .text { position: relative; top: -3px; } .heroes .badge { display: inline-block; font-size: small; color: white; padding: 5px 5px 5px 5px; background-color: #607D8B; position: relative; height: 25px; margin-right: .8em; border-radius: 4px 0 0 4px; } }

hero.component.ts

import { Component } from '@angular/core'; import { Hero } from './hero'; const HEROES : Hero[] = [ { id : 101, name : '张三'}, { id : 102, name : '李四'}, { id : 103, name : '王五'}, { id : 104, name : '赵六'}, { id : 105, name : '陈七'}, { id : 106, name : '吴八'} ]; @Component({ selector : 'my-app', templateUrl : './hero.component.html' }) export class HeroComponent{ title = '人物列表'; heroes = HEROES; selectedHero : Hero; onSelect(hero : Hero) : void { this.selectedHero = hero; } }

hero.ts

export class Hero { id : number; name : string; }

hero-details.component.html

<div *ngIf="hero"> <h2>大家好:我叫{{hero.name}}!</h2> <div><label>编号: </label>{{hero.id}}</div> <div> <label>姓名: </label> <input [(ngModel)]="hero.name" placeholder="name"/> </div> </div>

hero-details.component.ts

import { Component, Input } from '@angular/core'; import { Hero } from './hero'; @Component({ selector : 'hero-detail', templateUrl : './hero-details.component.html' }) export class HeroDateilComponent { @Input() hero : Hero; }

View

转载请注明原文地址: https://www.6miu.com/read-58030.html

最新回复(0)