本文主要介绍了angular4的输入属性与输出属性,结合实例形式详细分析了angular4输入属性与输出属性的概念、功能及相关使用技巧,需要的朋友可以参考下,希望能帮助到大家。
angular4输入属性
输入属性通常用于父组件向子组件传递信息
举个栗子:我们在父组件向子组件传递股票代码,这里的子组件我们叫它app-order
首先在app.order.component.ts中声明需要由父组件传递进来的值
order.component.ts
...
@input()
stockcode: string
@input()
amount: string
...
order.component.html
<p>这里是子组件</p>
<p>股票代码为{{stockcode}}</p>
<p>股票总数为{{amount}}</p>
然后我们需要在父组件(app.component)中向子组件传值
app.component.ts
...
stock: string
...
app.component.html
<input type="text" placeholder="请输入股票代码" [(ngmodel)]="stock">
<app-order [stockcode]="stock" [amount]="100"></app-order>
这里我们使用了angular的双向数据绑定,将用户输入的值和控制器中的stock进行绑定。然后传递给子组件,子组件接收后在页面显示。
angular4输出属性
当子组件需要向父组件传递信息时需要用到输出属性。
举个栗子:当我们从股票交易所获得股票的实时价格时,希望外部也可以得到这个信息。为了方便,这里的实时股票价格我们通过一个随机数来模拟。这里的子组件我们叫它app.price.quote
使用eventemitter从子组件向外发射事件
price.quote.ts
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
<p>
这里是报价组件
</p>
<p>
股票代码是{{stockcode}}
</p>
<p>
股票价格是{{price | number:'2.2-2'}}
</p>
接着我们在父组件中接收事件
app.component.html
<app-price-quote (pricechange)="pricequotehandler($event)"></app-price-quote>
<p>
这是在报价组件外, 股票代码是{{pricequote.stokccode}},
股票价格是{{pricequote.lastprice | number:'2.2-2'}}
</p>
事件绑定和原生的事件绑定是一样的,都是将事件名称放在()中。
app.component.ts
export class appcomponent{
pricequote:pricequote = new pricequote('', 0);
pricequotehandler(event:pricequote){
this.pricequote = event;
}
}
这里的event类型就是子组件传递事件的类型。
简单的说,就是子组件通过emit发射事件pricechange,并将值传递出来,父组件在使用子组件时会触发pricechange事件,接收到值。
相关推荐:
angular4中项目的准备和环境搭建操作
angular4中如何显示内容的css样式示例代码
angular4中路由router类的实例详解
以上就是详解angular4的输入属性与输出属性的详细内容。