【发布时间】:2020-12-24 05:31:33
【问题描述】:
我是 Angular 的新手,每次单击“添加地址”按钮时都想添加地址。我希望它是动态的,然后我将提交。
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: "", number: 0, street: "", unit: "", city: "", state: "", zipcode: ""},…]
0: {id: 0, type: "", number: 0, street: "", unit: "", city: "", state: "", zipcode: ""}
1: {id: 0, type: "", number: 0, street: "", unit: "", city: "", state: "", zipcode: ""}
2: {id: 0, type: "", number: 0, street: "", unit: "", city: "", state: "", zipcode: ""}
【问题讨论】:
-
请提供您的完整代码以便充分理解,并非常清楚地说明您计划实现的目标
-
我无法提供整个代码,因为它太长了。你需要什么?我只是得到处理地址的段。缺这个吗?
-
当您单击 addAddress 时,您的代码现在正在做什么,它将添加对象推送到您的数组中,并使用您在打字稿中初始化的值。当你提交时,把那个数组拿回来?如果这是流程,那么您的代码运行良好
-
是的,它应该将所有字段创建为输入元素,但它没有创建它。什么都没发生。应该有一个新创建的 li 元素,其中包含对象地址的所有输入,现在它什么都不做。
-
你是否订阅了一个可观察的联系人地址。从您的打字稿代码中,我可以看到“this.contact.Address.push(add)”和在您的 html 中“让添加contact.address | async”,请为您的地址中的“a”使用相同的大小写html 和打字稿