我制作了一个可重用的组件,它有一个反应式表单组。我有两个输入属性"name"one_answers"Description",我正在用ngFor设置这些输入属性来迭代组件。
不幸的是,即使我将表单控件组中的起始/默认值设置为输入属性,当我单击submit angular时,也会将这两个输入属性读取为"null",而不是通过输入属性设置的值。
表单组+输入属性:
@Input() categoryID;
@Input() categoryTitle;
@Input() categoryDescription;
categoryForm = new FormGroup({
categoryTitle: new FormControl(this.categoryTitle, [Validators.minLength(3), Validators.maxLength(50)]),
categoryDescription: new FormControl(this.categoryDescription, [Validators.minLength(5), Validators.maxLength(200)])
})
提交功能:
this.startLoading();
this.admin.updateCategory(this.categoryForm.value.categoryTitle, this.categoryForm.value.categoryDescription, this.categoryID)
如果我试图直接提交有效的输入属性的值,但如果我对表单进行修改,我将不再提交更改后的值,因此这没有意义。
组件视图初始化后,您应该创建FormGroup。因此,您可以实现AfterViewInit
,并将以下代码放在ngAfterViewInit
function
中。
ngAfterViewInit(){
this.categoryForm = new FormGroup({
categoryTitle: new FormControl(this.categoryTitle, [Validators.minLength(3), Validators.maxLength(50)]),
categoryDescription: new FormControl(this.categoryDescription, [Validators.minLength(5), Validators.maxLength(200)])
})
}