首页 文章

Angular7 Reactive Forms输入属性值在控制器/组件中不会更改,仅在HTML标记上更改

提问于
浏览
4

我制作了一个具有反应形式组的可重用组件 . 我有2个输入属性“名称”和“描述”,我正在使用ngFor设置这些输入属性来迭代组件 .

不幸的是,即使我将表单控件组中的start / default值设置为输入属性,当我单击submit angular时,将这两个输入属性读取为'null'而不是通过input属性设置的值 .

表单组输入属性:

@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)

如果我尝试直接提交有效的输入属性的值,但是如果我对表单进行修改,我就不再提交更改的值,这样就没有意义了 .

1 回答

  • 3

    初始化组件视图后,应创建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)])
      })
    }
    

相关问题