[英]Angular 2+: Update @Input property when parent value changes
我有一個父子組件,其中父組件通過 @Input 裝飾器將對象傳遞給子組件。 問題是孩子只獲取一次父數據,然后在將來更改傳遞給孩子的父屬性之后,該值不會被更新。
更改父組件時,也要更改子組件
這是檢測組件更改的OnChanges
接口的方法
在parent.component.html
<app-child [child_name]="name"></app-child>
在child.component.ts
export class ChildComponent implements OnChanges {
@Input('child_name') name: string
text: string
constructor() { }
// on every change of @input 'name', this method will be triggered
ngOnChanges() {
this.text = 'Hi ' + this.name
}
}
當整個參考將被更新時,數據將被更新。 如果您只是更新該對象內的某些屬性,則不會觸發它。 您需要更改傳遞對象的引用。
例子
<child [data]="myData"></child>
如果您將更新myData.name = "Test"
,它將不會被觸發。 你需要做點什么
this.myData = changedData;
一種解決方法是使用DoCheck
生命周期掛鈎並嘗試手動檢查屬性更改。 但通常更改參考會更方便。
如果您想從父組件獲取更新值,則需要在子組件中添加changeDetection: ChangeDetectionStrategy.OnPush
注意: OnPush 通過比較組件輸入的引用來工作
@Component({
selector: 'abc',
templateUrl: 'component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class childComponent {
//below get updated value every time value changes in parent
@Input() inputFromParent: string;
}
在父組件中,使用子組件abc
<abc [inputFromParent]="passdata"></abc>
in parent ts this.inputFromParent = newData;//第一次初始化后完成
現在,如果您更改passdata
的值,那么它也會更改 childcomponent 屬性中的值。
你的父 comp html 看起來像:
<div>
<span (click)="expandAllClient = true "> EXPAND </span>
<span (click)="expandAllClient = false"> COLLAPSE </span>
</div>
<div>
<child-comp [expandAll]="expandAllClient"(flagChanged)="flagChanged($event)"></child-comp>
</div>
不要忘記添加:
@Input() expandAll: boolean = false; in your ts file
在 child comp 中,您可以在所有操作中直接使用 expandall(here),例如:
<div [ngClass]="{'openPanel': expandAll}></div>
如果您單擊父組件中的 EXPAND 跨度,此處將應用 openpanel 類
嘗試通過 ngOnChanges 獲取更改
在子組件中使用
ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
}
您應該閱讀有關更改檢測的信息。
如果您想從父組件更改數據,而其他人使用service或ngrx-store也可以使用 redux
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.