Angular v8.1.9: Reactive Form not responding when value changes
I have a problem building a form using reactive form. The template is not responding as soon as the value changes only after I focus on an input the form is updated.
For example:
// app.component.html
< form [formGroup]="profileForm" (ngSubmit)="onSubmit()">
<label for="first-name">First Name: </label>
< input id="first-name" type="text" formControlName="firstName" required/>
<label for="last-name">Last Name: </label/>
< input id="last-name" type="text" formControlName="lastName"/>
<p>Complete the form to enable button.</p>
<em> Button is invalid</em>
< button type="submit" [disabled]="!profileForm.valid">Submit</button>
<hr>
<em>Not showing value right away</em>
<p>Form Value: {{ profileForm.value | json }}</p>
<em>Not showing value right away</em>
<p>Form Status: {{ profileForm.status }}</p>
</form> // app.component.ts
this.profileForm = this.fb.group({
firstName: ["", Validators.required],
lastName: [""],
});
setTimeout(() => {
this.profileForm.patchValue({
firstName: "Robert",
lastName: "Landis",
});
console.log(this.profileForm.value);
}, 1000); Replies (3)
Hi Matthew,
It seems like the issue is related to the Change Detection Strategy being set to <code>OnPush</code> in your <code>app.component.ts</code>. This strategy can sometimes cause the view to not respond immediately when the value changes.
To resolve this, you can try removing the <code>OnPush</code> strategy or handle the change detection manually. In your <code>app.component.ts</code>, you can do either of the following:
- Remove the Change Detection Strategy:
- Or manually trigger change detection:
By manually triggering the change detection with <code>this.cdr.detectChanges();</code>, the view should update immediately when the value changes. This should resolve the issue with the form not responding as expected.
Please give this a try and let me know if it resolves the problem. If you have any further questions or encounter any other issues, feel free to ask for more assistance.
Thanks
Hi
,
Great! If you need any further help please let us know.
All the best with your projects!
Regards.