问题描述
我是新来的有角用户,想每次单击按钮“添加地址”时添加地址。我希望它是动态的,然后我将提交。
HTML:
<div class="form-group">
<label for="name">Address: </label>
<div>
<button type="button" class="btn btn-info" (click)="addAddress()" >Add Address</button>
</div>
<div>
<ul>
<li *ngFor="let add of contact.address | async">
<label for="name">Type</label>
<input type="text" class="form-control" id="atype" required [(ngModel)]="add.type" name="atype">
....
</li>
</ul>
</div>
</div>
TS:
addAddress() {
let add = {
id: 0,type: '',number: 0,street: '',unit: '',city: '',state: '',zipcode: ''
};
this.contact.Address.push(add);
}
当我单击它时,除了我提交时什么都不做
我创建了空数组:
Address: [{id: 0,type: "",street: "",unit: "",city: "",state: "",zipcode: ""},…]
0: {id: 0,zipcode: ""}
1: {id: 0,zipcode: ""}
2: {id: 0,zipcode: ""}
解决方法
小写和大写的错字:
在TS代码中使用大写的地址,在模板上使用小写:
this.contact.Address
还有另一个问题,重复使用id
属性,您将在模板中获得重复ID。
除非必须,否则应避免在模板中使用id。如果必须在模板中使用id,则应使id唯一。
已通过堆栈闪电修复:
https://stackblitz.com/edit/template-driven-form-example-pvdhhh?file=src/app/app.component.html