欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Angular6學(xué)習(xí)筆記之主從組件

 更新時(shí)間:2018年09月05日 14:56:24   作者:wujiayucn  
這篇文章主要介紹了詳解Angular6學(xué)習(xí)筆記之主從組件,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

主從組件

繼學(xué)習(xí)筆記6,現(xiàn)在可以在頁(yè)面上顯示一個(gè)數(shù)組,但是原則上不能將所有特性放在同一個(gè)組件中,因?yàn)槿绻麑⑺刑匦苑旁谕粋€(gè)組件中,當(dāng)特性特別多時(shí),組件就變得不好維護(hù)了。所以要將大型組件拆分為多個(gè)小型組件,使每一個(gè)小型組件集中處理某一個(gè)特性任務(wù)或者工作流,而且這樣也便于維護(hù)。

這次要將學(xué)習(xí)筆記6中的查看hero詳情,放置在一個(gè)新的,獨(dú)立,可復(fù)用的組件中,集中在新的組件管理和維護(hù)hero詳情的信息。

1.創(chuàng)建一個(gè)新的組件

使用 Angular CLI 生成一個(gè)名叫 hero-detail 的新組件。

wjydeMacBook-Pro:demo wjy$ ng generate component hero-detail
CREATE src/app/hero-detail/hero-detail.component.css (0 bytes)
CREATE src/app/hero-detail/hero-detail.component.html (30 bytes)
CREATE src/app/hero-detail/hero-detail.component.spec.ts (657 bytes)
CREATE src/app/hero-detail/hero-detail.component.ts (288 bytes)
UPDATE src/app/app.module.ts (548 bytes)

這樣就生成了 HeroDetailComponent 組件所需要的文件,并把它聲明在 AppModule 中。

2.編寫(xiě) HeroDetailComponent的模版(hero-detail.component.html)

從 HeroesComponent 模板的底部把表示英雄詳情的 HTML 代碼剪切粘貼到所生成的 HeroDetailComponent 模板中。

粘貼過(guò)來(lái)的html代碼中,有selectHero這個(gè)屬性,由于現(xiàn)在我們展示的不僅僅是被選中的hero,而是需要展示的是每一個(gè)hero,這個(gè)過(guò)程相當(dāng)于將HeroDetail這個(gè)組件的功能擴(kuò)大化。所以將其更改為:hero , hero-detail.component.html如下:

<div *ngIf="hero">
 <h2>{{hero.name | uppercase}} Details</h2>
 <div><span>id: </span>{{hero.id}}</div>
 <div>
  <label>name:
   <input [(ngModel)]="hero.name" placeholder="name"/>
  </label>
 </div>
 
</div>

因?yàn)镠eroDetail重的hero是從其他父組件得到。所以hero 屬性必須是一個(gè)帶有 @Input() 裝飾器的輸入屬性,因?yàn)橥獠康?HeroesComponent 組件將會(huì)綁定到它。

具體步驟:

導(dǎo)入Hero

import { Hero } from '../hero';

導(dǎo)入Input符號(hào)

import { Component, OnInit, Input } from '@angular/core';

定義hero

@Input() hero: Hero;

這樣,就對(duì)heroDetail的類(lèi)文件寫(xiě)好了,heroDetail所做的工作就是:從其他的父組件中接收一個(gè)Hero類(lèi)型的對(duì)象,并將它展示出來(lái)

3.顯示 HeroDetailComponent

現(xiàn)在有HeroDetail組件顯示每一個(gè)Hero的具體詳情信息,而Heroes組件需要顯示每一個(gè)Hero的詳細(xì)信息,這個(gè)時(shí)候,Heroes組件和heroDetail組件就有了主從關(guān)系,heroes組件需要將需要展示詳情的Hero對(duì)象傳給具有展示功能的HeroDetail組件

HeroDetailComponent 的選擇器是 'app-hero-detail'。 把 <app-hero-detail> 添加到 HeroesComponent 模板的底部,以便把英雄詳情的視圖顯示到那里,并把 HeroesComponent.selectedHero 綁定到該元素的 hero 屬性, HeroesComponent模版即:

<h2>My Heroes</h2>
<ul class="heroes">
 <li *ngFor="let hero of heroes" (click)="onSelect(hero)" [class.selected]="hero === selectedHero">
  <span class="badge">{{hero.id}}</span> {{hero.name}}
 </li>
</ul>
<app-hero-detail [hero]="selectedHero"></app-hero-detail>

保存瀏覽器刷新,界面和之前的不會(huì)有變化,但是會(huì)有一下優(yōu)點(diǎn):

  • 通過(guò)縮減 HeroesComponent 的職責(zé)簡(jiǎn)化了該組件。
  • 把 HeroDetailComponent 改進(jìn)成一個(gè)功能豐富的英雄編輯器,而不用改動(dòng)父組件 HeroesComponent。
  • 改進(jìn) HeroesComponent,而不用改動(dòng)英雄詳情視圖。
  • 將來(lái)可以在其它組件的模板中重復(fù)使用 HeroDetailComponent。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論