欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

Angular4的輸入屬性與輸出屬性實例詳解

本文實例講述了Angular4的輸入屬性與輸出屬性。分享給大家供大家參考,具體如下:

武江網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),武江網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為武江成百上千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站建設(shè)要多少錢,請找那個售后服務(wù)好的武江做網(wǎng)站的公司定做!

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>股票總數(shù)為{{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的雙向數(shù)據(jù)綁定,將用戶輸入的值和控制器中的stock進行綁定。然后傳遞給子組件,子組件接收后在頁面顯示。

Angular4輸出屬性

當子組件需要向父組件傳遞信息時需要用到輸出屬性。

舉個栗子:當我們從股票交易所獲得股票的實時價格時,希望外部也可以得到這個信息。為了方便,這里的實時股票價格我們通過一個隨機數(shù)來模擬。這里的子組件我們叫它app.price.quote

使用EventEmitter從子組件向外發(fā)射事件

price.quote.ts

export class PriceQuoteComponent implements OnInit{
 stockCode: string = 'IBM';
 price: number;
 //使用EventEmitter發(fā)射事件
 //泛型是指往外發(fā)射的事件是什么類型
 //priceChange為事件名稱
 @Output()
 priceChange:EventEmitter<PriceQuote> = new EventEmitter();
 constructor(){
  setInterval(() => {
   let priceQuote = new PriceQuote(this.stockCode, 100*Math.random());
   this.price = priceQuote.lastPrice;
   //發(fā)射事件
   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>
<div>
 這是在報價組件外, 股票代碼是{{priceQuote.stokcCode}},
 股票價格是{{priceQuote.lastPrice | number:'2.2-2'}}
</div>

事件綁定和原生的事件綁定是一樣的,都是將事件名稱放在()中。

app.component.ts

export class AppComponent{
 priceQuote:PriceQuote = new PriceQuote('', 0);
 priceQuoteHandler(event:PriceQuote){
  this.priceQuote = event;
 }
}

這里的event類型就是子組件傳遞事件的類型。

簡單的說,就是子組件通過emit發(fā)射事件priceChange,并將值傳遞出來,父組件在使用子組件時會觸發(fā)priceChange事件,接收到值。

更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS指令操作技巧總結(jié)》、《AngularJS入門與進階教程》及《AngularJS MVC架構(gòu)總結(jié)》

希望本文所述對大家AngularJS程序設(shè)計有所幫助。

文章標題:Angular4的輸入屬性與輸出屬性實例詳解
網(wǎng)頁路徑:http://chinadenli.net/article24/gjeoje.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、響應(yīng)式網(wǎng)站ChatGPT、網(wǎng)站設(shè)計公司、移動網(wǎng)站建設(shè)全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)