我整理了一个非常简单的角度形式,其中一个按钮应该在用户单击时动态添加文本字段。我错过了一些东西,因为当我单击“添加”按钮时,它不会动态添加新的文本框。 有人可以告诉我我在想什么,
app-component.ts`
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
feedbackForm: FormGroup;
constructor(private fb: FormBuilder) { }
ngOnInit() {
this.feedbackForm = this.fb.group({
goodFeedback: this.fb.array([])
});
}
get goodFeedback() {
return this.feedbackForm.get('goodFeedback') as FormArray;
}
addGoodFeedback() {
this.goodFeedback.push(this.fb.control(''));
}
}
app-component.html
<div class="container-fluid">
<h2>Add Feedback</h2>
<form [formGroup]="feedbackForm">
<div class="form-group">
<label>Good Feedback</label>
<button type="button" class="btn btn-secondary btn-sm m-2" (click)="addGoodFeedback()">Add</button>
<input type="text" formControlName="goodfeedback" class="form-control">
<div formArrayName="goodfeedback" *ngFor="let goodfeedback of goodfeedback.controls; let i=index">
<input type="text" class="form-control my-1" [formControlName]="i">
</div>
</div>
</form>
</div>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
答案 0 :(得分:0)
我进行了Stackblitz解决了您的问题:Stackblitz
在视图中,我只是将let goodfeedback of goodfeedback.controls
行替换为let feedback of feedbackForm.get('goodFeedback').controls
。
我认为,当您在表单的controls
数组中添加控件时,Angular不会看到该数组已更改,因此当您使用let goodfeedback of goodfeedback.controls
遍历控件时,它会看到controls
为空。