【发布时间】:2017-12-16 15:21:11
【问题描述】:
当我删除一个地址并添加一个新地址时,我遇到了一个错误。旧地址会被新地址覆盖。
我创建了一个小型演示应用程序来展示我的问题:
github:https://github.com/kolomu/HeroDemo
堆栈闪电战:https://stackblitz.com/edit/angular-gitter-5o6ydi
不是模型错了,不知怎么角度渲染的视图没有正确更新。
查看:
<form #heroForm="ngForm">
<div class="form-group">
<div class="addresses" *ngFor="let address of model.addresses; let i=index">
<label for="address-{{i}}">Address {{i}}</label>
<input type="text" class="form-control" [(ngModel)]="address.location" name="location-{{i}}">
<button class="btn btn-danger" (click)="remove(address)">Remove Address</button>
</div>
</div>
<button class="btn btn-primary" (click)="add()">Add Address</button>
</form>
组件类:
export class HeroFormComponent {
model = new Hero(18, 'Dr IQ', [new Address(1,'main','Earth'), new Address(9001,'sub','Moon')]);
remove(address) {
const index = this.model.addresses.findIndex(
address => address.id === address.id
);
this.model.addresses.splice(index, 1);
}
add(){
this.model.addresses.push(new Address());
}
}
数据模型:
export class Address {
constructor(public id?: number, public type?:string, public location?: string) { }
}
export class Hero {
constructor(
public id: number,
public name: string,
public addresses: Address[]
) { }
}
展示问题的 GIF 图片: https://gfycat.com/DelightfulSpiffyBetafish
【问题讨论】:
标签: angular angular-forms