[英]Two way databinding and change detection with child components in Angular 2-6
我有一個從父組件使用的組件。 看起來像這樣:
export class AttributeComponent implements OnInit, OnChanges {
@Input() attribute: CharacterAttribute;
@Output() attributeChange = new EventEmitter<CharacterAttribute>();
ngOnChanges(changes: SimpleChanges): void {
this.attributeChange.emit(this.attribute);
}
}
我使用此代碼的目的是將對輸入模型的任何更改發送回父級。 在父級中,我使用以下代碼創建實例:
<app-attribute [(attribute)]="character.str"></app-attribute>
在組件內部,對於模型的每個屬性,我都有以下代碼:
<label>Base <input type="text" pInputText [(ngModel)]="attribute.base"></label>
但是,ngOnChanges永遠不會觸發,綁定只是一種方法。 我該如何進行雙向綁定?
如果正確設置了@Inputs() ,並且已在父組件的組件DOM上附加了適當的屬性 ,則NgOnChanges會在所有其他掛鈎之前觸發。
建立單獨的輸入/輸出流或使用主題或傳遞整個對象(由於傳遞了引用,因此您可以在兩端自由地修改其屬性)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.