Angular应用里的@Input和@Output注解使用方法介绍
這一對注解用于在parent上下文和子指令或者組件之間共享數(shù)據(jù)。@Input修飾的屬性可寫,用于數(shù)據(jù)綁定,而@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.
假設(shè)有這樣一對父子Component:
<parent-component><child-component></child-component> </parent-component>可以把@Input和@Output想象成一對API, 父子組件間通過API進行通信。@Input相當(dāng)于inbound接口,允許數(shù)據(jù)流入子Component,而@Output允許子Component往外發(fā)送數(shù)據(jù)。
@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中間件里,我們談?wù)摂?shù)據(jù)流向時,視角是從SAP CRM出發(fā)的,凡是數(shù)據(jù)從ERP流向CRM,即CRM從ERP下載數(shù)據(jù),所以稱為download. 反之,從CRM推送數(shù)據(jù)到ERP,稱為upload.
而Angular里的@input和@output,視角同樣是從child Component來說的。
 
被@Input修飾的子Component屬性,可以使用Angular生命周期hook OnChanges來監(jiān)控。
@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的方式發(fā)送數(shù)據(jù)給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的事件處理函數(shù):
export class AppComponent {items = ['item1', 'item2', 'item3', 'item4'];addItem(newItem: string) {this.items.push(newItem);} }要獲取更多Jerry的原創(chuàng)文章,請關(guān)注公眾號"汪子熙":
 
總結(jié)
以上是生活随笔為你收集整理的Angular应用里的@Input和@Output注解使用方法介绍的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 日积跬步02
- 下一篇: 哈啰打车推免佣、高额满单奖等车主激励举措
