【问题标题】:Dynamic create li when you click add button angular 7单击添加按钮 angular 7 时动态创建 li
【发布时间】: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 和打字稿

标签: html angular angular7


【解决方案1】:

小写和大写的错字:

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

this.contact.Address

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

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

已修复堆栈闪电战:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 2020-04-12
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多