I have been trying to resolve this for a while and have tried several solutions from stackoverflow with no luck. e.g. @ViewChild in *ngIf
It was working ok when I loaded the customer on init but now I subscribe to the user and customer and this is causing problems.
When I click the save button (from outside the form) to trigger the form onSubmit it does not work as formCustomerDetailsRef is undefined even if I have a valid customer and I can see the form.
I have also tried using changeDetector.detectChanges(); and ngZone however these did not help.
I tried the following technique but it did not work either: https://stackoverflow.com/a/41095677/10222449
I am using Angular 8.
export class HomeComponent implements OnInit, OnDestroy {
@ViewChild('formCustomerCtrl', { static: false }) formCustomerDetailsRef: FormGroupDirective;
...
ngOnInit(): void {
const sub = this.authService.currentAppUser$.subscribe(appUser => {
this.appUser = appUser;
if (appUser) {
this.getCustomer();
this.getSettings();
this.getCountries();
}
}
...
getCustomer() {
const sub = this.customerService.currentCustomer$.subscribe(async customer => {
this.customer = customer;
...
onSubmitCustomerForm() {
this.formCustomerDetailsRef.onSubmit(undefined);
}
<ng-container *ngIf="customer">
<div *ngIf="fbUserAuthClaims?.admin" class="button btn_2" (click)="onSubmitCustomerForm()">
<img src="assets/icons/link.svg">Save Changes
</div>
...
<article *ngIf="tabCompanyProfileSelected">
<form *ngIf="customer" [formGroup]="formCustomerDetails" (ngSubmit)="onUpdateCustomer()" #formCustomerCtrl="ngForm">
...
Alternative code which also does not work:
private formCustomerDetailsRef: FormGroupDirective;
@ViewChild('formCustomerCtrl', { static: false }) set content(content: FormGroupDirective) {
if (content) { // initially setter gets called with undefined
this.formCustomerDetailsRef = content;
}
}