I have a tempate-driven form, built several years ago, with about 20 input fields (Showing one input as an example). The validation is working as expected. However, when the api is called to submit the form, there might be a message or instruction to the user such as retry (due to timeout, etc.).
If the user updates the form, and invalidates the form, and then fixes the entries, I want to clear the message(s) or instructions when the form becomes valid again.
Note: if the form is already valid and there is a message or instruction, I want to keep the message or instruction. Actually, the message or instruction can be cleared once any field is changed (not necessarily valid).
<div *ngIf="!examForm.form.valid" class="text-danger pe-3">Please complete all required fields. </div>
<div *ngIf="errState && examForm.form.valid" class="text-danger pe-3">{{statusMessage}}</div>
<form class="form" #examForm="ngForm" (ngSubmit)="examForm.form.valid && saveExam()" novalidate>
:
<div class="col-4">
<input class="form-control form-control-sm fs-6 inputrx" type="text" value=""
min="-12" max="12" step="0.25" placeholder="{{rxPlaceholder}}"
[pattern]="rxPattern" id="rxStr" name="rxStr"
required [(ngModel)]="rxOut" #rxStr_mod="ngModel"
[disabled]='rxIsReadOnly' (focusout)="onExamItemFocusOut($event)"
[ngClass]="(rxStr_mod.errors?.pattern || rxStr_mod.errors?.required) ? 'rx_invalid_value' : ''" />
</div>
:
</form>
I thought I could just subscribe (per another post with similar requirment using Angular 2) to the statusChanges event...
import { Component, OnInit, ViewChild, TemplateRef, Input } from '@angular/core';
import { AbstractControl, NgForm } from '@angular/forms';
export class ExamFormComponent implements OnInit {
:
public errState: boolean = false;
@ViewChild('examForm') examForm: NgForm;
:
constructor(){
}
ngAfterViewInit() {
this.examForm.statusChanges //VSCode says this.examForm is possibly null
.pipe(
filter(() => this.examForm.form.valid)) //VSCode says filter is deprecated
.subscribe(() => this.onFormValid());
}
onFormValid(){
//clear messages or instruction since form became valid
this.errState = false;
console.log("=========================== onFormValid called!")
}
}
I was under the impression that the @ViewChild would bind to the instance, but it seems I'm missing somthing.
VsCode and ng serve/build
error TS2531: Object is possibly 'null'. this.examForm.valueChanges
Currenlty using Angular 14.
Any ideas?
Not sure what other ways to subscribe an isValidating event (if there is any).
Checked several post - most using Angualr 2.