日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Angular应用里的@Input和@Output注解使用方法介绍

發布時間:2023/12/19 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Angular应用里的@Input和@Output注解使用方法介绍 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

這一對注解用于在parent上下文和子指令或者組件之間共享數據。@Input修飾的屬性可寫,用于數據綁定,而@Output屬性可被訂閱(Observable).

@Input() and @Output() allow Angular to share data between the parent context and child directives or components. An @Input() property is writable while an @Output() property is observable.

假設有這樣一對父子Component:

<parent-component><child-component></child-component> </parent-component>

可以把@Input和@Output想象成一對API, 父子組件間通過API進行通信。@Input相當于inbound接口,允許數據流入子Component,而@Output允許子Component往外發送數據。

@Input() and @Output() act as the API, or application programming interface, of the child component in that they allow the child to communicate with the parent. Think of @Input() and @Output() like ports or doorways—@Input() is the doorway into the component allowing data to flow in while @Output() is the doorway out of the component, allowing the child component to send data out.

Use the @Input() decorator in a child component or directive to let Angular know that a property in that component can receive its value from its parent component. It helps to remember that the data flow is from the perspective of the child component. So an @Input() allows data to be input into the child component from the parent component.

如何理解Angular這對input和output的流向?類似SAP CRM中間件里的download和upload. 在SAP中間件里,我們談論數據流向時,視角是從SAP CRM出發的,凡是數據從ERP流向CRM,即CRM從ERP下載數據,所以稱為download. 反之,從CRM推送數據到ERP,稱為upload.

而Angular里的@input和@output,視角同樣是從child Component來說的。


被@Input修飾的子Component屬性,可以使用Angular生命周期hook OnChanges來監控。

@Output

被@output修飾的子Component屬性,一般通過Angular EventEmitter初始化,通過events的方式流出子Component.

An @Output() property should normally be initialized to an Angular EventEmitter with values flowing out of the component as events.

例子:

子Component里定義一個property:

@Output() newItemEvent = new EventEmitter();

如何通過Event的方式發送數據給parent Component?

export class ItemOutputComponent {@Output() newItemEvent = new EventEmitter<string>();addNewItem(value: string) {this.newItemEvent.emit(value);} }

child Component的html:

<label>Add an item: <input #newItem></label> <button (click)="addNewItem(newItem.value)">Add to parent's list</button>

如何在parent Component里接收來自child Component的事件?

<app-item-output (newItemEvent)="addItem($event)"></app-item-output>

newItemEvent是子Component加了@Output注解的property名稱,addItem是父Component的事件處理函數:

export class AppComponent {items = ['item1', 'item2', 'item3', 'item4'];addItem(newItem: string) {this.items.push(newItem);} }

要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":

總結

以上是生活随笔為你收集整理的Angular应用里的@Input和@Output注解使用方法介绍的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。