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

标签 angular angular-reactive-forms angular-forms angular7 angular-changedetection

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

不幸的是,即使我将表单控件组中的开始/默认值设置为输入属性,当我单击提交时,angular 会将这 2 个输入属性读取为“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)

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

最佳答案

您应该在组件 View 初始化后创建 FormGroup。所以你可以实现AfterViewInit,把下面的代码放在ngAfterViewInitfunction中。

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)])
  })
}

关于Angular7 Reactive Forms 输入属性值不会在 Controller /组件中更改,仅在 HTML 标记上更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53049821/

相关文章:

javascript - 为什么每次请求都会发送 cookie,但在浏览器控制台或 document.cookie 中看不到?

javascript - mat 表,可通过验证在行中动态添加行和可编辑字段

angular - 检查后表达式发生了变化。先前值 : 'ng-valid: true' . 当前值: 'ng-valid: false'

Angular react 形式未定义值

angular - 如何将自定义服务注入(inject)另一个自定义服务?

javascript - 为什么我的共享服务未在我的组件之间更新?

angular - 使用Docker在AWS EC2中进行Spring Boot微服务部署

Angular : How to check if some control exist in form or not

javascript - 如何通过函数将 `linkRef`更新为 `touched`状态?

angular - 在另一个 FormArray 中嵌套 FormArray