如何遍历角度复选框使其变为动态?

时间:2018-11-14 10:45:50

标签: javascript angular typescript angular6

我有一个类似以下内容的经过编码的复选框:

enter image description here

代码如下:

<h5>Document List</h5>
<div class="form-check">
   <label class="form-check-label" for="check1">
   <input type="checkbox" class="form-check-input" id="check1" name="proformaInvoice" value="something" [(ngModel)]="processAnexOne.proformaInvoice" value="checked" >Proforma Invoice
   </label>
</div>

即将到来的Json数据是:

enter image description here

调用api获取json数据的方法是:

ngOnInit() {
         this.http.get('http://localhost:8080/api/documents')
      .subscribe((data: any[]) => {
        this.documents = data;
        console.log(this.documents);
      })
  }

我如何将这些json数据合并到复选框中,使其变为动态?

3 个答案:

答案 0 :(得分:1)

您可以使用b遍历*ngFor。注意:您可以在documents中添加一个属性,您可以在document中的bind中使用value。在这里,我添加了属性checkbox

selected

答案 1 :(得分:0)

在您的HTML中,用ngIf检查数据是否已经到达。如果不是,则不显示div。

在内部div中,对文档运行ngFor。

<h5>Document List</h5>
<div class="form-check" *ngIf="dataIsPresent">
  <div *ngFor="let document of documents">
   <label class="form-check-label" for="check1">
   <input type="checkbox" class="form-check-input" name="document.docName" value="something"  value="document.docName" >{{document.docName}}
   </label>
  </div>
</div>

在TS中创建一个布尔值,以检查数据是否到达。

dataIsPresent: Boolean = false;
ngOnInit() {
         this.http.get('http://localhost:8080/api/documents')
      .subscribe((data: any[]) => {
        this.documents = data;
        this.dataIsPresent = true;
        console.log(this.documents);
      })
  }

让我知道这是否有帮助。

答案 2 :(得分:0)

您可以使用* ngFor指令来迭代文档并创建复选框

<div *ngFor="let obj of documents">
    <div class="form-check">
       <label class="form-check-label" for="check1">
           <input type="checkbox" class="form-check-input" id="check1"
           name="proformaInvoice" value="something" 
           [(ngModel)]="obj.value" value="checked" >Proforma 
           Invoice
       </label>
    </div>
</div>