angularngmodelangular2-form-validation

Form validations with ngModel and ngModelOption in angular 8


I'm using angular 8 with formGroup and formController for validation which works great through reactive as well as template-driven form. However, I was trying to use "ngModel" in angular 8 with "ngModelOptions" attributes (it's a dynamically generated fields). It shows field level validations correctly with "required" attribute, but I'm unable prevent button click or disable the "button" on error validation state. A sample code is given below:

<form [formGroup]="myForm" #form1="ngForm">
 <!-- few formControlName fields here -->
<mat-form-field>
   <input matInput [(ngModel)]="firstname" [ngModelOptions]="{standalone: true}" [placeholder]="First name" required />
   <mat-error>This field is <strong>required</strong></mat-error>
</mat-form-field>
<mat-form-field>
   <input matInput [(ngModel)]="lastname" [ngModelOptions]="{standalone: true}" [placeholder]="Last name" required />
   <mat-error>This field is <strong>required</strong></mat-error>
</mat-form-field>
<button mat-button [disabled]="!(form1.form.valid)">Submit</button>
</form>

Submit button never disabled in spite of the blank first name and last name fields. I understand When you mark it as standalone: true this will not happen (it will not be added to the FormGroup). But is there any workaround or other approaches where I can achieve the ngModel validations to restrict the form submission on the button?


Solution

  • if you put in the same tag

    <form [formGroup]="myForm" #form1="ngForm">
    

    "form1" is myForm, and "firstName" and "lastName" don't belong to myForm.

    if you use

    [ngModelOptions]="{standalone: true}"
    

    your input don't belong to any form.

    You can add in your inputs #firstnameID="ngModel" and #lastnameID="ngModel" and ask about firstnameID.valid and lastnameID.valid

    <form [formGroup]="myForm" #form1="ngForm">
     <!-- few formControlName fields here -->
    <mat-form-field>
       <input matInput [(ngModel)]="firstname" 
            #firstnameID="ngModel"
            [ngModelOptions]="{standalone: true}" 
            placeholder="First name" required />
       <mat-error>This field is <strong>required</strong></mat-error>
    </mat-form-field>
    <mat-form-field>
       <input matInput [(ngModel)]="lastname" 
           #lastnameID="ngModel"
           [ngModelOptions]="{standalone: true}" 
           placeholder="Last name" required />
       <mat-error>This field is <strong>required</strong></mat-error>
    </mat-form-field>
    <button mat-button [disabled]="!(myForm.valid) ||
                                   !firstnameID.valid ||
                                   !lastnameID.valid">Submit</button>
    </form>
    

    NOTE: I suppose it's not the answer you expect but it's in this way