我有以下代码来创建一行和一个按钮Add Person。在单击Add person时,我想与Person 2,Person 3等再创建一个行。
。我该怎么做到。
<div class="splitTheBill-row">
<div class="splitTheBill-left">
<div class="userIcon">
<div class="splitTheBill-user">
<img src="assets/images/person.png" alt="My Profile">
</div>
<div class="input-field national-id pull-left">
<input id="form3" class="form-control" type="text">
<label for="form3" class="">Person 1</label>
</div>
</div>
</div>
<div class="splitTheBill-right">
<div class="input-field national-id pull-left">
<input id="form4" class="form-control" type="text">
</div>
</div>
</div>
<div class="addperson-btncont">
<div class="reg-submitCont">
<button url="#" class="btn-secondary waves-effect waves-light btn">Add Person</button>
</div>
</div>
答案 0 :(得分:4)
您需要使用*ngFor
来遍历您的人员,就像这样:
<div class="splitTheBill-left">
<div *ngFor="let person of persons">
<div class="userIcon">
<div class="splitTheBill-user">
<img src="assets/images/person.png" alt="My Profile">
</div>
<div class="input-field national-id pull-left">
<input id="form3" class="form-control" type="text">
<label for="form3" class="">{{person.name}}</label>
</div>
</div>
</div>
</div>
然后,您可以在TS中创建一个代表人物的数组:
persons = [
{"name": "Person 1"}
]
要添加新行,您需要做的就是将一个新人员推送到该数组中
this.persons.push({"name": "Person " + (this.persons.length + 1)})
答案 1 :(得分:1)
我认为您在这里寻找的是一种反应式表格,该表格可以将即时添加的人添加到表格中:
这是一个最小的模板:
ImportWarning
这是组件类:
<form [formGroup]="personsForm" (submit)="onFormSubmit()">
<div formArrayName="persons">
<div *ngFor="let person of persons; let i = index;" [formGroupName]="i">
Name: <input type="text" formControlName="name"><br>
Amount: <input type="text" formControlName="amount">
</div>
</div>
<button type="button" (click)="addPerson()">
Add Person
</button>
<button>
Submit
</button>
</form>
这是您推荐的Sample StackBlitz。