如何动态使用ng-for获取输入框和复选框 [英] How to dynamically use ng-for to get input boxes and checkbox
本文介绍了如何动态使用ng-for获取输入框和复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是有角度的应用程序.我的要求是:在输入框中输入的数字(record.accountRoles,如下所示)上,我希望div中的元素重复.
This is angular app. My requirement is :upon the number entered inside input box (record.accountRoles, shown below), I want elements inside div to be repeated.
<!-- input box -->
<div class="form-group">
<label for="name">Enter the number of accounts</label>
<input type="text" class="form-control" [(ngModel)]="record.accountRoles" name="accountsRoles" required>
</div>
<!-- div elements that must be repeated -->
<div *ngFor="let i of record.accountRoles.length">
<label for="name">AccountId</label>
<input type="text" class="form-control" [(ngModel)]="record.roles[i].accountid" name="accountid" required>
<mat-checkbox [(ngModel)] = "record.roles[i].role">
<label>IT Admin</label>
</mat-checkbox>
</div>
这是初始化记录变量的方式
This is how record variable is initialized
record = {firstName:null,lastName:null,emailAddress:null,accountRoles:null,roles:[{accountid:null,role:null}]};
推荐答案
将您的html更改为:
Change your html to:
<div class="form-group">
<label for="name">Enter the number of accounts</label>
<input type="text" class="form-control" [(ngModel)]="record.accountRoles" (change)="updateAccounts()"name="accountsRoles" required>
</div>
<!-- div elements that must be repeated -->
<div *ngFor="let item of record.roles">
<label for="name">AccountId</label>
<input type="text" class="form-control" [(ngModel)]="item.accountid" name="accountid" required>
<mat-checkbox [(ngModel)] = "item.role">
<label>IT Admin</label>
</mat-checkbox>
</div>
如果需要使用索引,则使用
If you need the index for something use:
*ngFor="let item of record.accountRoles; let i = index"
将组件更改为:
record = {firstName:null,lastName:null,emailAddress:null,accountRoles:1,roles:[{accountid:null,role:null}]};
updateAccounts () {
this.record.roles = [];
for(let i = 0 ; i< this.record.accountRoles; i++)
this.record.roles.push({accountid:null,role:null});
}
https://stackblitz.com/edit/angular-nzuc9h?file=src%2Fapp%2Fapp.component.html
这篇关于如何动态使用ng-for获取输入框和复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文