[英]Update an object array via ngmodel from a child component Angular
我對 React 更熟悉。 我的問題似乎很普遍。
首先,我有一個 TreeDataStructure class。在這個 class 中,我有一個“過濾器”屬性,用於保存應用於 memory 中的樹的過濾器。
樹存儲在組件 A 的屬性中。我將樹的“過濾器”屬性轉移到組件 B,A 的子組件。
該子組件一一顯示所有過濾器,B 的子組件 C 顯示單個過濾器並允許對其進行修改。
我擔心的是,我無法獲取組件 A 中存儲的從 C 到 TreeDataStructure class 的過濾器更改。
這是我的代碼的要點:
樹數據結構.ts
export class DataTreeStructure {
filters: Filters;
}
type Filters = {
items: Array<Filter>
linkOperator: LinkOperator //and or or
}
type Filter = {
column: string
operator: string
comparaisonValue: string
}
組分A
export class ComponentA {
tree: DataTreeStructure
}
組件 A 模板
<component-b filters[tree.filters]></component-b>
B組份
export class ComponentB {
@Input() filters: Filters;
}
組分 B 模板
<ng-container *ngFor="let item of filters.items; let index = index;">
<component-c
[column]="filters.items[index].column"
[operator]="filters.items[index].operator"
[comparaisonValue]="filters.items[index].comparaisonValue"
>
</component-c>
</ng-container>
組件 C
export class ComponentC {
@Input() column: string;
@Input() operator: string;
@Input() comparaisonValue: string;
}
組件 C 模板
<input [(ngModel)]="column"/>
<input [(ngModel)]="operator"/>
<input [(ngModel)]="comparaisonValue"/>
你會怎么做?
要從組件 C 更新 TreeDataStructure class 的過濾器屬性,您可以結合使用 Input 和 Output 裝飾器。 這是一種方法:
在組件 C 中創建一個 Output 事件發射器以發射更新的過濾器值。
@Output() filterChanged = new EventEmitter<Filter>();
在組件 C 的模板中,當過濾器值更改時發出事件。
<input [(ngModel)]="column" (ngModelChange)="emitFilterChanged()"/>
<input [(ngModel)]="operator" (ngModelChange)="emitFilterChanged()"/>
<input [(ngModel)]="comparaisonValue"
(ngModelChange)="emitFilterChanged()"/>
在組件 C class 中,創建一個方法以使用更新的過濾器值發出事件。
emitFilterChanged() {
this.filterChanged.emit({
column: this.column,
operator: this.operator,
comparaisonValue: this.comparaisonValue
});
}
在組件 B 中,創建一個方法來處理 filterChanged 事件並更新 TreeDataStructure 的 filters 屬性 class。
handleFilterChanged(filter: Filter, index: number) {
this.filters.items[index] = filter;
}
trackByFn(index: any, item: any) {
return index;
}
在組件B的模板中,將過濾器的索引和handleFilterChanged方法傳遞給組件C,並在handleFilterChanged方法上綁定filterChanged事件。
<ng-container *ngFor="let item of filters.items; let index = index; trackBy:trackByFn">
<component-c
[column]="filters.items[index].column"
[operator]="filters.items[index].operator"
[comparaisonValue]="filters.items[index].comparaisonValue"
(filterChanged)="handleFilterChanged($event, index)"
>
</component-c>
</ng-container>
通過使用此方法,您現在可以從組件 C 更新 TreeDataStructure class 的過濾器屬性,並且更改將反映在組件 A 中。
使用 TrackBy Angular 可以根據唯一標識符跟蹤哪些項目已添加(或刪除),並僅創建或銷毀更改的內容,這意味着您不會失去對輸入字段的關注:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.