ts 文件:
this.addAdvertise = this.formBuilder.group({
input1: [''],
input2: [''],
.
.
.
inputN: [''],
desc: ['']
});
输入计数来自数组的长度,数组来自服务器。
是否可以使用 for 循环创建输入控件?
你可以写一个简单的for循环:
let group = {};
for (let i = 0; i < myArray.length; i++) {
group[`input${i+1}`] = [..];
}
this.addAdvertise = this.formBuilder.group(group);
是的,您在离子 2 或 3 中使用了反应式形式和表单模块,
将此代码添加到您的 app.module.ts 文件中,
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
@NgModule({
...
imports: [
ReactiveFormsModule,
FormsModule
]
...
})
export class AppModule {}
将此代码添加到组件文件中,
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
name:string;
dynamicForm:any = FormGroup;
ngOnInit() {
}
constructor(private fb: FormBuilder){
this.dynamicForm = this.fb.group({
properties: this.fb.array([])
});
}
addProperty() {
for(var i=1; i<=1; i++) {
<FormArray>this.dynamicForm.get('properties').push(new FormControl());
}
}
}
将此代码添加到您的 HTML 文件中,
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button (click)="addProperty()">Add Property</button>
<form [formGroup]="dynamicForm">
<div formArrayName="properties">
<div *ngFor="let prop of dynamicForm.get('properties').controls; let i = index " >
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>
</form>
<br>
<pre>{{dynamicForm.value | json }}</pre>
</ion-content>
谢谢