我试图通过点击按钮添加多个表单字段。为了实现这一点,我使用了一个数组,因此只需单击一个按钮就可以推送数组元素,并根据数组中的项目生成表单。在那个表单中,我有一个select字段,由另一个数组填充。字段生成正常,但选择不填充。
app.component.ts
import { Component } from "@angular/core";
import { test } from './test';
@Component({
selector: "app-root",
templateUrl: './app.component.html'
})
export class AppComponent {
mytest: test[] = [];
fields: string[] = ['First Name','Last Name','Email Address','Address1 ','Address2 ','City','Postal Code','Province']
add() {
this.mytest.push({name: 't',type: 't',placeholder:'t',values:'t'});
console.log(this.mytest);
}
}
app.component.html
<form #formRef="ngForm">
<div *ngFor="let word2 of mytest; let in=index" class="col-sm-3">
<div class="form-group">
<select id="fe[in]">
<option *ngFor="let f of fields">{{f}}</option>
</select>
<input type="text" [(ngModel)]="word2[in].name" name="name{{in}}" class="form-control" #name="ngModel" required />
</div>
<br />
</div>
<button [disabled]="!formRef.form.valid" (click)="add()">Add input</button>
</form>
test.ts
export interface test{
name: string;
type: string;
placeholder: string;
values: string;
}