In Angular template driven form I want to validate input fields conditionally, based on which button was clicked. Then in the ts component file I check whether the form is valid i.e action can be executed or invalid i.e form data needs to be corrected. I use the form template reference variable to determine if form is valid or not <form #heroForm="ngForm">, then in the .ts file @ViewChild('heroForm') form:Ngform;
When a button is clicked I set the condition whether the field is required or not and then evaluate whether the form is valid or not.
However, when I set the variable actionType = 'A' so that the input is required and then right after evaluate this.form.valid it tells me the form is valid even though it is not ( required input is missing data)
this.actionType = 'A';//this make the input field required
if(this.form.valid){ // should be false but it is true (although later it changes to false)
//code that should be executed when form is valid
}
After I debugged the app I noticed that setting a variable with new value then running validation is done asynchronously, therefore this.form.valid is checked before previous operation is finished.
When I put the form checking code inside setTimeout it works but I am not sure this is the correct way to handle this case.
Is there any other way this should or can be solved?
I created a stackblitz sample to illustrate the problem https://stackblitz.com/edit/angular-g1nb9s
Watch the console output to see what is happening.
Expected behaviour:
- I click actionA button
- input field becomes required by setting
actionType = 'A' - value of
this.form.validin ts file should befalse( because input is required and is empty)
Currently when I click actionA button and read immediately this.form.valid in component file, then the value is true
falseas soon as you click button a. Unless I'm extremely dumb and not noticing something obvious. - SiddAjmera