【发布时间】:2020-07-16 05:34:54
【问题描述】:
我有一个包含对象数组的父组件。
我使用 *ngFor 循环通过 @Input() 使用每个索引处的元素填充子组件。
如果我更改索引处的对象,子组件会完全重置,而不是仅仅接受新的 Input 并维护它的其他属性。
Stackblitz minimal example
打字稿:
export interface MyObject {
a: string;
b: string;
}
export class Parent {
objectArray: MyObject[] = [
{a: 'string A', b: 'string B'}
];
changeAnObject() {
const sameObject: MyObject = {a: 'string A', b: 'string B'};
this.objectArray[0] = sameObject;
}
}
export class Child {
@Input() inputObject: MyObject;
selected = false; // Some other property to maintain
}
父 HTML:
// 3 different ways to populate inputObject
<div *ngFor="let object of objectArray">
<app-child [inputObject]="object"></app-child> // does not maintain "selected" property
</div>
<div *ngFor="let object of objectArray; let index = index">
<app-child [inputObject]="objectArray[index]"></app-child> // does not maintain "selected" property
</div>
<div>
<app-child [inputObject]="objectArray[0]"></app-child> // DOES maintain "selected" property
</div>
<button (click)="changeAnObject()">Change Object</button>
子 HTML:
<div (click)="selected = !selected">
a: {{inputObject.a}}
b: {{inputObject.b}}
SELECTED: {{selected}}
</div>
结果
在父 HTML 中,[inputObject]="objectArray[0]" 是我发现的唯一解决方案,它在更改 objectArray[0] 中的元素时保持 Child 的其他属性。
这对我来说不够好,因为我有很多对象要展示。
有没有更好的方法将数据发送到组件而不完全重置它们?
我曾尝试将Angular Accessors 与@Input() set inputObject {...} 一起使用,但它无法维护组件的属性。也就是说,当inputObject 发生变化时,构造函数会再次执行,将所有属性重置为默认值。
【问题讨论】:
-
如果您使用
push()而不是按索引直接插入对象,那么行为是否相同?this.objectArray.push(sameObject); -
@XavierBrassoud,这与添加新对象的效果不同,无论如何都需要创建一个新的额外的
。那肯定会创建一个新的 并将其设置为默认属性。
标签: javascript arrays angular typescript ngfor