我正在使用表单,并试图动态地将文本区域添加到它。但当我点击添加按钮时,它工作正常,但它改变了所有以前的值与新的文本区域的值。
我已经尝试提取代码,但没有使它工作在stackblitz(这里是我的尝试。https:/stackblitz.comeditangular-ivy-tns7nv?file=src%2Fapp%2Fapp.component.html)。)
我也试着删除了this.changesDetector.detectChanges();但还是不行,而且出现了一个错误。ExpressionChangedAfterItHasBeenCheckedError(错误)
这是我的代码:.ts:
import {
Component,
Input,
OnChanges,
OnInit,
ChangeDetectorRef
} from "@angular/core";
import {
FormBuilder,
FormControl,
FormGroup,
Validators
} from "@angular/forms";
export interface BlockComment {
id?: any;
comment?: string;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
finalComment: string[] = [];
formProjet1: FormGroup;
blockComment: BlockComment[] = [
{
id: 0,
comment: ""
}
];
constructor(
private formBuilder: FormBuilder,
private changesDetector: ChangeDetectorRef
) {}
ngOnInit() {
this.initForm();
}
initForm() {
this.formProjet1 = this.formBuilder.group({
comments: new FormControl("")
});
}
addTextareaComment() {
const id = new Date().getTime().toString();
this.blockComment.push({
id,
comment: "TEST" // <-- THIS VALUE
});
this.changesDetector.detectChanges();
}
private getComments(): string[] {
this.finalComment = [];
for (const comment of this.blockComment) {
this.finalComment.push(comment.comment);
}
return this.finalComment;
}
}
.html
<div>
<form name="formProjet1" [formGroup]="formProjet1" class="repeater">
<button (click)="addTextareaComment()" class="btn btn-primary ">Add comm</button>
<br>
<div>
<div>
<div class="form-group">
<div class="row" *ngFor="let block of blockComment">
<div class="col-md-9">
<textarea class="form-control"
type="text"
name="comments"
formControlName="comments"
[(ngModel)]="block.comment">
</textarea>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
你有每 textarea
势同水火 formControlName="comments"
. 一个表单控件--一个值。你需要 FormArray 而不是。
该属性 blockComment
将无法与 FormArray
. 将所有的数据都存储在 "数据仓库 "中会更实用。FormArray
而不是散布于 blockComment
和 FormArray
.
PS你需要手动调用来检测变化,因为 this.blockComment.push
不更新在 blockComment
. 更多关于数组和变化检测的细节,请参见本篇文章。.