Utilizing NgForm, I dynamically added a validator to the input field.
In my first example, everything works perfectly when I use the button setValidation to validate the input. However, in the second example where I add formGroup, I encounter an error when clicking the button setValidation:
Cannot read property 'setValidators' of null
@ViewChild('f') myForm: NgForm;
coumNameModel;
setValidation() {
this.myForm.form.get('coumnName').setValidators([Validators.required, Validators.pattern("^[0-9]*$"), Validators.minLength(2), Validators.maxLength(2)]);
this.myForm.form.get('coumnName').updateValueAndValidity();
}
First Example
<form #f="ngForm">
<input type="text" [(ngModel)]="coumnNameModel" name="coumnName" #coumnName="ngModel">
</form>
<p *ngIf="!myForm.form.get('coumnName')?.valid">
<i class="icons icon-cancel color-error"></i>
<small class="color-error">Invalid</small>
</p>
<button (click)="setValidation()">Set Validation</button>
Second Example
<form [formGroup]="generalInformationForm" #f="ngForm">
<input type="text" [(ngModel)]="coumnNameModel" name="coumnName" #coumnName="ngModel" gDefaultControl
[ngModelOptions]="{standalone: true}">
</form>
<p *ngIf="!myForm.form.get('coumnName')?.valid">
<i class="icons icon-cancel color-error"></i>
<small class="color-error">Invalid</small>
</p>
<button (click)="setValidation()">Set Validation</button>