我正在開發一個Angular 4.X項目,並試圖在按鈕單擊時創建一些HTML輸入字段(主要是文本類型)。我正在使用Angular反應形式並試圖使用Angular FormArray來實現這一點。我已經將代碼寫入了重定向程序,但它顯示了一些錯誤。在Angular 2中動態創建輸入字段
以下是我創建的鏈接普拉克 - http://plnkr.co/edit/PCFD43GK91zo2ivQ9lf7?p=preview
爲了便於參考,請找到下面的代碼 -
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'my-app',
template: `<hr>
<div>
<form [formGroup]="orderForm" (ngSubmit)="OnSubmit(orderForm.value)">
<div>
<input type="text" formControlName="customerName"/>
<input type="text" formControlName="email"/>
</div>
<div formArrayName="items" *ngFor="let item of orderForm.get('items').controls; let i = index;">
<div [formGroupName]="i">
<input type="text" formControlName="name" placeholder="Item name"/>
<input type="text" formControlName="description" placeholder="Item description"/>
<input type="text" formControlName="price" placeholder="Item price"/>
</div>
Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>
<button type="submit">Save</button>
<button type="button" (click)="addItem()">Add More</button>
</form>
<div>`,
})
export class App {
constructor(private fb: FormBuilder) { }
public items:any[];
public orderForm: FormGroup;
ngOnInit() {
this.orderForm = this.formBuilder.group({
customerName: '',
email: '',
items: this.formBuilder.array([ this.createItem()])
});
}
createItem(): FormGroup {
return this.formBuilder.group({
name: '',
description: '',
price: ''
});
}
addItem(): void {
this.items = this.orderForm.get('items') as FormArray;
this.items.push(this.createItem());
}
public OnSubmit(formValue: any) {
console.log(formValue);
}
}
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
如果有人能弄清楚什麼是錯的,我將非常感謝。
看看我給[這裏](https://stackoverflow.com/a/44767953)的答案,可能是一個解決方案。 – BogdanC