Angular2快速入门-3.多个组件(分离新闻列表页和…
2018-06-24 00:51:52来源:未知 阅读 ()
上篇(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中注册。
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:github相关问题
- javascript面向对象入门基础详细介绍 2020-03-29
- Jquery 快速构建可拖曳的购物车DragDrop 2019-09-30
- 入门webpack,看这篇就够了 2019-08-14
- 剑指前端(前端入门笔记系列)——BOM 2019-08-14
- 剑指前端(前端入门笔记系列)——DOM(元素大小) 2019-08-14
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash
