typescript 使用 Angular 4 检查来自父组件的表单是否有效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44943981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:41:28  来源:igfitidea点击:

Check if a form is valid from a parent component using Angular 4

angulartypescript

提问by D.B

I am trying to check the validity of a form placed on a child component from a parent component. The best scenario would be to disable a button on the parent component if the form is invalid or in the worse scenario to trigger an alert from the parent button if form is invalid.

我正在尝试从父组件检查放置在子组件上的表单的有效性。如果表单无效,最好的情况是禁用父组件上的按钮,或者在更糟糕的情况下,如果表单无效,则从父按钮触发警报。

I could achieve to check if the form has 'ng-invalid' class from the parent using a @ViewChild decorator to call a function on the child component as follows:

我可以使用@ViewChild 装饰器来检查表单是否具有来自父级的“ng-invalid”类来调用子组件上的函数,如下所示:

Parent Component:

父组件:

export class CandidateVerificationComponent implements OnChanges, OnInit {

@ViewChild(RightPanelComponent) rightPanelPointer: RightPanelComponent;

saveAndFinish() {

    if (this.rightPanelPointer.checkFormValidity())
    {
        alert('No Valid');
        return;
    }

    this.rightPanelPointer.onSubmit();

  }    
}

Child Component:

子组件:

export class RightPanelComponent implements OnChanges , OnInit{

@ViewChild("candiateForm", { read: ElementRef }) tref: ElementRef;

   checkFormValidity():boolean {        
    return (this.tref.nativeElement.className.indexOf('ng-invalid') !== -1);
   }  
}

It works for the worst scenario, but I do not like the idea to link the component to the DOM, I would rather a smarter idea.

它适用于最坏的情况,但我不喜欢将组件链接到 DOM 的想法,我更喜欢更聪明的想法。

I would like to use a template reference variable (#candiateForm), for example the one that allows to check validity in the submit button (see below) from the form (child) in order to check validity from the parent. Is it possible to have access to that template variable from the parent?

我想使用模板引用变量 (#candiateForm),例如允许检查表单(子)提交按钮(见下文)中的有效性以检查父项有效性的变量。是否可以从父级访问该模板变量?

 <form (ngSubmit)="onSubmit()" #candiateForm="ngForm" name="candiateForm" (change)="formChanged()">
    <div class="form-group">
      <label class="control-label" for="firstName">First name:</label>                           
      <input type="text" class="form-control" id="firstName" pattern="^[^0-9]+$" required [(ngModel)]='candidate.firstName' name="firstName" #firstName="ngModel">
   </div>
<button type="submit" class="btn btn-default" [disabled]="!candiateForm.form.valid">Submit</button>
</form>

回答by Max Koretskyi

Since Angular applies ngFormto all formelements implicitly and you can reference any component/directive in the component template by component/directive class reference, you don't have to read ElementRefand don't need the template reference #candiateForm, you can access the form directly by the directive class reference ngForm:

由于 Angular隐式适用ngForm于所有form元素,并且您可以通过组件/指令类引用来引用组件模板中的任何组件/指令,因此您不必阅读ElementRef也不需要模板引用#candiateForm,您可以通过指令类参考ngForm

export class RightPanelComponent implements OnChanges , OnInit{
    @ViewChild(NgForm) form;

    checkFormValidity():boolean {        
        return this.form.valid;
    }

And also you can access the form directly from the parent component:

您也可以直接从父组件访问表单:

export class CandidateVerificationComponent implements OnChanges, OnInit {
    @ViewChild(RightPanelComponent) rightPanelPointer: RightPanelComponent;

    saveAndFinish() {
        if (this.rightPanelPointer.form.valid)