1. 程式人生 > >Angular2快速入門-3.多個組件(分離新聞列表頁和詳細頁)

Angular2快速入門-3.多個組件(分離新聞列表頁和詳細頁)

中新 table ref date 入門 log sta ble row

上篇(Angular2快速入門-2.創建一個新聞列表)已經完成新聞列表的展示,並且點擊新聞列表的時候,下面可以展示出新聞的詳細信息,這節我們把新聞詳細和新聞列表頁面分離出來

新聞詳細單獨一個component

第一、創建news-detail.component

1)創建news-detail.component.ts

import {Component,Input} from ‘@angular/core‘;
import {News} from  ‘./news‘;

@Component({
    selector:‘news-detail‘,
    templateUrl:‘./news-detail.component.html‘,
    styleUrls:[‘newslist.component.css‘]    
})
export class NewsDetailComponent{
   @Input() news:News;
}

2)創建news-dtail.component.html

<div *ngIf="news">
    <h3>新聞詳細</h3>
    <table>
        <tr>
            <td>id:</td>
            <td> {{news.id}}</td>
        </tr>
        <tr>
            <td>title:</td>
            <td>
                <input [(ngModel)]="news.title" placeholder="title" />
            </td>
        </tr>
    </table>
</div>

news-dtail.component.html : 把原先在newslist.component.html 中新聞詳細頁的模板內容剪切到 此處

修改 newslist.component.html

<h2>新聞列表</h2>
<ul class="ul_news">
    <li *ngFor="let n of newlist" (click)="onSelected(n)" >
        {{n.id}}.{{n.title}} <span>{{n.create_date}}</span>        
    </li>
</ul>

<news-detail [news]="selectedNew"></news-detail>

  

newslist.component.html : 增加新的新聞詳細模板標簽 <news-detail [news]="selectedNew"></news-detail>

註意此處的 [news]="selectedNew"這種寫法,這是屬性綁定(需要我們在類中 設置屬性綁定標簽@Input(),可以看new-detail 類), 即news-dtail.component 的屬性 news 需要newslist.component.ts中的selectedNew 賦給

新聞詳細模板中有個news屬性,該屬性的值是新聞列表中的selectedNew賦給的。

第二、把news-dtail組件增加到app.module上去

上面已經完成new-detail 的詳細組件,但是並不work,還需要我們把新增加到 NewsDetailComponent 類增加到啟動模塊中,

具體修改 app.module.ts

import { BrowserModule } from ‘@angular/platform-browser‘;
import { NgModule } from ‘@angular/core‘;
import { FormsModule } from ‘@angular/forms‘;

import { NewsListComponent } from ‘./news/newslist.component‘;
import { NewsDetailComponent } from ‘./news/news-detail.component‘;
import { AppComponent } from ‘./app.component‘;

@NgModule({
  declarations: [
    AppComponent,
    NewsListComponent,
    NewsDetailComponent  
  ],
  imports: [
    BrowserModule,
    FormsModule 
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

命令行,執行npm start,可以看到程序運轉起來和上篇完全一樣,但是我們把新聞列表和新聞詳細都獨立開來,便於重復利用。

第三、總結

1.註意屬性執行令@Input 的使用,需要在@angular/core 中引入類Input,屬性綁定時候使用中括號內寫屬性,例如:<news-detail [news]="selectedNew"></news-detail>

2. 新增加的Component 一定要在app.module.ts中註冊。

Angular2快速入門-3.多個組件(分離新聞列表頁和詳細頁)