angular - 如何在 Angular 11 中创建嵌套表单数组
问题描述
我正在尝试在角度 11 中嵌套表单数组。截至目前,我已经尝试过这样的操作,并且工作正常。
spinner: boolean = false;
new_created: boolean = true;
create_question_form: FormGroup;
group: any = new FormGroup({
name: new FormControl(''),
});
constructor(private route: ActivatedRoute, private fb: FormBuilder) {}
validation() {
this.create_question_form = this.fb.group({
question: new FormArray([this.group]),
});
}
get question() {
return this.create_question_form.get('question') as FormArray;
}
add_question() {
this.question.push(this.group);
}
create_question() {
const data = this.create_question_form.getRawValue();
console.log(data);
}
ngOnInit(): void {
this.validation();
this.add_question();
}
<form
[formGroup]="create_question_form"
(ngSubmit)="create_question()"
>
<ng-container formArrayName="question">
<div *ngFor="let _ of question.controls; index as i">
<ng-container [formGroupName]="i">
<div class="col-12 col-md-4 mt-5">
<span class="p-float-label w-100">
<input
type="text"
id="inputtext"
class="form-control"
formControlName="name"
pInputText
/>
<label for="inputtext">Name</label>
</span>
</div>
</ng-container>
</div>
</ng-container>
<button type="submit" class="btn btn-success">Create</button>
</form>
但我想要的是在我的 Formgroup 中创建一个新的 FormArray (Address),就像这样。
group: any = new FormGroup({
name: new FormControl(''),
address:new FormArray([]),
});
我不知道如何在我的 HTML 中访问这个地址表单数组,或者如何在这个数组中推送新的 FormControl。
解决方案
添加新组:
this.group.controls.address.push(new FormGroup({street: new FormControl('')}));
用于访问该添加的组:
this.group.controls.address['controls'][0]['controls']['street'].value
删除该组:
let group_arr = (this.group.controls.address as FormArray);
group_arr.removeAt(index)
推荐阅读
- android - Flutter:禁用选项卡导航直到表单验证完成
- php - PHP 无法检索 SQL Server 2016 存储过程的 BEGIN CATCH...END CATCH 块中分配的 [结果代码] 和 [输出参数]
- c# - 加载函数调用时,我可以在后台进程中运行 Outlook 附加方法吗?
- unity3d - UI 文本水平溢出换行模式
- python - 如何添加/计算“余额”行?
- c# - 传入复杂类型参数并在 MVC Action 中设置默认值?
- api - 使用简单的 https 请求更新 Firestore 数据库(云)上的单个字段
- c++ - 如何从动态内存中正确删除对象的指针?
- javascript - sidenav 覆盖在粘性导航栏顶部,sidenav 覆盖的高度有问题
- python - 将句子分成新行