我是靠谱客的博主 无心小蜜蜂,这篇文章主要介绍Angular4的输入属性与输出属性实例详解,现在分享给大家,希望可以做个参考。

本文实例讲述了Angular4的输入属性与输出属性。分享给大家供大家参考,具体如下:

Angular4输入属性

输入属性通常用于父组件向子组件传递信息

举个栗子:我们在父组件向子组件传递股票代码,这里的子组件我们叫它app-order

首先在app.order.component.ts中声明需要由父组件传递进来的值

order.component.ts

复制代码
1
2
3
4
5
6
... @Input() stockCode: string @Input() amount: string ...

order.component.html

复制代码
1
2
3
<p>这里是子组件</p> <p>股票代码为{{stockCode}}</p> <p>股票总数为{{amount}}</p>

然后我们需要在父组件(app.component)中向子组件传值

app.component.ts

复制代码
1
2
3
... stock: string ...

app.component.html

复制代码
1
2
<input type="text" placeholder="请输入股票代码" [(ngModel)]="stock"> <app-order [stockCode]="stock" [amount]="100"></app-order>

这里我们使用了Angular的双向数据绑定,将用户输入的值和控制器中的stock进行绑定。然后传递给子组件,子组件接收后在页面显示。

Angular4输出属性

当子组件需要向父组件传递信息时需要用到输出属性。

举个栗子:当我们从股票交易所获得股票的实时价格时,希望外部也可以得到这个信息。为了方便,这里的实时股票价格我们通过一个随机数来模拟。这里的子组件我们叫它app.price.quote

使用EventEmitter从子组件向外发射事件

price.quote.ts

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
export class PriceQuoteComponent implements OnInit{ stockCode: string = 'IBM'; price: number; //使用EventEmitter发射事件 //泛型是指往外发射的事件是什么类型 //priceChange为事件名称 @Output() priceChange:EventEmitter<PriceQuote> = new EventEmitter(); constructor(){ setInterval(() => { let priceQuote = new PriceQuote(this.stockCode, 100*Math.random()); this.price = priceQuote.lastPrice; //发射事件 this.priceChange.emit(priceQuote); }) } ngInit(){ } } //股票信息类 //stockCode为股票代码,lastPrice为股票价格 export class PriceQuote{ constructor(public stockCode:string, public lastPrice:number ) }

price.quote.html

复制代码
1
2
3
4
5
6
7
8
9
<p> 这里是报价组件 </p> <p> 股票代码是{{stockCode}} </p> <p> 股票价格是{{price | number:'2.2-2'}} </p>

接着我们在父组件中接收事件

app.component.html

复制代码
1
2
3
4
5
<app-price-quote (priceChange)="priceQuoteHandler($event)"></app-price-quote> <div> 这是在报价组件外, 股票代码是{{priceQuote.stokcCode}}, 股票价格是{{priceQuote.lastPrice | number:'2.2-2'}} </div>

事件绑定和原生的事件绑定是一样的,都是将事件名称放在()中。

app.component.ts

复制代码
1
2
3
4
5
6
export class AppComponent{ priceQuote:PriceQuote = new PriceQuote('', 0); priceQuoteHandler(event:PriceQuote){ this.priceQuote = event; } }

这里的event类型就是子组件传递事件的类型。

简单的说,就是子组件通过emit发射事件priceChange,并将值传递出来,父组件在使用子组件时会触发priceChange事件,接收到值。

更多关于AngularJS相关内容感兴趣的读者可查看本站专题:《AngularJS指令操作技巧总结》、《AngularJS入门与进阶教程》及《AngularJS MVC架构总结》

希望本文所述对大家AngularJS程序设计有所帮助。

最后

以上就是无心小蜜蜂最近收集整理的关于Angular4的输入属性与输出属性实例详解的全部内容,更多相关Angular4内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(139)

评论列表共有 0 条评论

立即
投稿
返回
顶部