Reputation: 51
I am new to angular, wanted to add address every time click the button "Add Address". I wanted it to be dynamic then I will submit.
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);
}
when I click it does nothing but when I submit
I got empty arrays created:
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: ""}
Upvotes: 1
Views: 1130
Reputation: 8623
Typo on the lower case and upper case:
Use the upper case Address in TS code, and the lower case on template:
this.contact.Address
There is also another issue, using id
attribute in a repeat, you will get repeat ids in the template.
We should avoid using id in the template unless we have to, if we have to use the id in template, we should make the id unique.
Fixed on stackblitz:
https://stackblitz.com/edit/template-driven-form-example-pvdhhh?file=src/app/app.component.html
Upvotes: 1