I have a parent component and a child component. The child has a form which needs to be saved if the user has changed it and tries to navigate away by clicking a link on the parent.
Parent
@Component({
selector: 'parent',
templateUrl: './parent.html',
providers: [MessageService]
})
export class ParentComponent {
@ViewChild('child') child: ChildComponent;
message: any;
The ChildComponent has a form with lots of data entered. It also has an object called user which must have permission to save the form.
child
save() {
if (this.user.role <= 2) postFormDataToDb();
In the parent, when a link is clicked to navigate away, it calls
this.child.save();
The error I get is that this.child is null. I could be wrong, but it seems like ChildComponent is a new instance with everything empty, rather than the existing one. Yet it seems like the form is in the DOM since I can inspect one of the fields and it shows up.
I've tried several different approaches but all produce a null error. I've tried using a shared MessageService and subscribing to it.
this.subManager = this.messageService.getMessage().subscribe(message => {
this.message = message;
console.log("message=",message);
});
this.sendMessage('save');
but the message never gets to the button (nothing shows up in the div).
<div *ngIf="message" (click)="saveUsers()">{{message.text}}</div>
I've tried loading just the #saveBtn from the child form
@ViewChild('saveBtn') saveBtn: ElementRef;
and clicking it with
this.saveBtn.nativeElement.click();
from the parent component. Error says this.saveBtn is null.
The provided link seems like it might be a duplicate question, but the solutions involve *ngIf which I don't use, except to display the message.
What am I missing?