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);
Hi Matthew,
It seems like the issue is related to the Change Detection Strategy being set to OnPush
in your app.component.ts
. This strategy can sometimes cause the view to not respond immediately when the value changes.
To resolve this, you can try removing the OnPush
strategy or handle the change detection manually. In your app.component.ts
, you can do either of the following:
1. Remove the Change Detection Strategy:
// Remove this line if you have set the Change Detection Strategy to OnPush
// import { ChangeDetectionStrategy } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
// Remove the Change Detection Strategy if set to OnPush
// changeDetection: ChangeDetectionStrategy.OnPush,
})
import { ChangeDetectorRef } from "@angular/core";
// ...
constructor(private fb: FormBuilder, private cdr: ChangeDetectorRef) {
this.profileForm = this.fb.group({
firstName: ["", Validators.required],
lastName: [""],
});
setTimeout(() => {
this.profileForm.patchValue({
firstName: "Robert",
lastName: "Landis",
});
console.log(this.profileForm.value);
this.cdr.detectChanges(); // Manually trigger change detection
}, 1000);
}
this.cdr.detectChanges();
, the view should update immediately when the value changes. This should resolve the issue with the form not responding as expected.Thanks for you help! I already solved it.
Hi ,
Great! If you need any further help please let us know.
All the best with your projects!
Regards.