单击添加按钮时动态创建 li angular 7

Dynamic create li when you click add button angular 7

我是 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: ""}

大小写错别字:

在TS代码中使用大写地址,在模板中使用小写:

this.contact.Address

还有一个问题,在repeat中使用id属性,你会在模板中得到repeat ids。

除非必须,否则我们应该避免在模板中使用id,如果我们必须在模板中使用id,我们应该使id唯一。

已在 stackblitz 上修复:

https://stackblitz.com/edit/template-driven-form-example-pvdhhh?file=src/app/app.component.html