【问题标题】:How to determine if child component form is valid in parent component when using reactive forms使用反应式表单时如何确定子组件表单在父组件中是否有效
【发布时间】:2017-12-12 11:31:58
【问题描述】:

我正在使用带有响应式表单的 Angular 5

子组件类:

export class UserEditor implements OnInit {

    public userForm: FormGroup;

...

ngOnInit() {
    this.createFormControls();
    this.createForm();
}
createFormControls() {
    this.userName = new FormControl('', [
        Validators.required,
        Validators.minLength(4)
    ]);
    this.firstName = new FormControl('', Validators.required);
    this.lastName = new FormControl('', Validators.required);
    this.email = new FormControl('', [
      Validators.required,
      Validators.pattern("[^ @]*@[^ @]*")
    ]);

}
createForm() {
 this.userForm = new FormGroup({
      userName: this.userName,
      name: new FormGroup({
        firstName: this.firstName,
        lastName: this.lastName,
      }),
      email: this.email,
    });
}

在我的父组件表单中,如果上述验证器无效,我的按钮将被禁用

在父组件html中:

<button class="btn btn-sm  btn-primary" (click)="saveUser()" [disabled]="!userListChild?.userForm.valid">

在父组件类中:

export class UserList implements OnInit {
     @ViewChild(UserEditor) userListChild: UserEditor;

一切正常,但是我得到了众所周知的错误

ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:“真”。当前值:'假

我尝试了此博客中列出的更改检测解决方案,但没有帮助。

https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

所以我被卡住了,除非我忽略错误,因为应用程序可以正常处理错误。

【问题讨论】:

    标签: angular angular5 angular-validation


    【解决方案1】:

    我正在回答列出几个解决方案:

    1 - 尝试将 ngOnInit 替换为 ngAfterViewChecked

    2 - 在您的 ngOnInit 中,尝试添加一个 setTimeout(() =&gt; /* calls */) 您将两个方法调用都置于超时状态

    【讨论】:

      【解决方案2】:

      如果你使用这个库https://github.com/cloudnc/ngx-sub-form会更简单

      我已经回复了一个与这里https://stackoverflow.com/a/56375605/2398593 非常相似的答案,所以我认为提供比那里更多的代码没有任何用处。

      请在此处查看我为该答案制作的演示 https://stackblitz.com/edit/so-question-angular-2-large-scale-application-forms-handling,在那里您将能够看到与您的结构相似的东西

      注意到错误部分了吗?即使您有子表单,您也可以从父组件访问它并查看表单中的问题!

      【讨论】:

        猜你喜欢
        • 2021-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-05
        • 1970-01-01
        • 1970-01-01
        • 2017-12-10
        相关资源
        最近更新 更多