问题
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}]};
回答1:
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"
Change your component to:
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
来源:https://stackoverflow.com/questions/57707339/how-to-dynamically-use-ng-for-to-get-input-boxes-and-checkbox