天天看點

ionic入門之多元件開發模式

版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/inforstack/article/details/71276112

在實戰中建議是用多元件開發模式,高耦合低内聚。

檔案名群組件名遵循風格指南中的标準方式。

  1. 元件的類名應該是大駝峰形式,并且以Component結尾。 是以英雄詳情元件的類名是HeroDetailComponent。
  2. 元件的檔案名應該是小寫中線形式,每個單詞之間用中線分隔,并且以.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

繼續閱讀