Form validation is not working in angular?

前端 未结 3 1260
生来不讨喜
生来不讨喜 2020-12-21 23:00

I want to check whether the dropdown is empty.

Need to show the required message and

If not empty, enable the submit button.

If empty, disable the

3条回答
  •  悲哀的现实
    2020-12-21 23:49

    You are currently assigning formcontrols to your formcontrol, whereas you want to assign value to your form controls. Below you are assigning form control name to formcontrol name:

    WRONG:

    name = new FormControl('', Validators.required);
    
    this.myForm = this.formBuilder.group({
      'name': [this.name, Validators.required],
      // ...
    });
    

    so instead, just declare name, do what you want with the value, then assign that value to your form control...

    CORRECT:

    name: string;
    
    this.myForm = this.formBuilder.group({
      'name': [this.name, Validators.required],
      // ...
    });
    

    Then just add [disabled]="!myForm.valid" on your submit button.

    As for the other question, by default Angular material doesn't show error message unless the field has been touched, so you need to have a custom error state matcher that shows the error even when field is not touched (if that is what you want):

    import {ErrorStateMatcher} from '@angular/material/core';
    
    export class MyErrorStateMatcher implements ErrorStateMatcher {
      isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
        return !!(control.invalid);
      }
    }
    

    and in your TS, declare a error state matcher:

    matcher = new MyErrorStateMatcher();
    

    and use in template:

    
    

    Here's your

    StackBlitz

提交回复
热议问题