首页 > 其他 > 详细

Angular2快速入门-3.多个组件(分离新闻列表页和详细页)

时间:2017-11-23 10:37:58      阅读:218      评论:0      收藏:0      [点我收藏+]

上篇(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.多个组件(分离新闻列表页和详细页)

原文:http://www.cnblogs.com/clc2008/p/7883412.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!