Angular Material - show mat-error on button click

后端 未结 10 1795
刺人心
刺人心 2021-02-02 07:48

I am trying to do validation using the and . This works fine when user tabs out of the input without filling. B

相关标签:
10条回答
  • 2021-02-02 08:28

    You can also easily call the AbstractControl.updateValueAndValidity() function on button click. This will run the validation process on the corresponding ForControl again and show errors, if there are some (based on your Validators).

    So, in your example:

        checkForErrorsOnButtonClick(): void {
          dueDateValidator.updateValueAndValidity();
        }
    
    0 讨论(0)
  • 2021-02-02 08:29

    Since you want to show mat error on button's click, please try the below: For Angular6 version:

    1). import below:
        import { FormControl, FormBuilder, FormGroup } from '@angular/forms';
    
    2). declare form control in .ts file:
        nameControl = new FormControl('');
    
    3). put control in html:
        <mat-form-field  style="width: 100%" floatPlaceholder="never">
          <input matInput placeholder="your placeholder text" [formControl]="nameControl" 
            required/>
          <mat-error *ngIf="nameControl.errors?.required">name is required</mat-error>
        </mat-form-field>
    
    3). on button's click:
        this.nameControl.markAsTouched();
    

    It's important to check how you are using the form control, ".markAsTouched()" on point 3 will show the mat error for the corresponding form control.

    0 讨论(0)
  • 2021-02-02 08:30

    I am providing 3 different solutions for different scenarios, use the one which suits you.

    • If you are using a form, then do

      this.form.markAllAsTouched();
      
    • If you need a particular field to be affected inside form, then filter that nameControl and do

      nameControl.markAsTouched();
      
    • If you are not using forms, then specify a ref for the input element and initialize variable in ts file & do as follows,

      @ViewChild('myInputRef') myInputRef; // Initialize the ref of input element
      .
      .
      this.myInputRef.control.markAsTouched()
      
    0 讨论(0)
  • 2021-02-02 08:35

    Angular 8 has a new forms method: markAllAsTouched();

    This will mark a control/form and ALL DESCENDANTS as touched!!!

    So:

    this.form.markAllAsTouched();
    

    Is the solution.

    0 讨论(0)
提交回复
热议问题