I'm dealing with both a parent component and a child component in my project. The child component contains a form that should be saved if the user makes changes and then tries to navigate away by clicking on a link within the parent component.
Parent Component
@Component({
selector: 'parent',
templateUrl: './parent.html',
providers: [MessageService]
})
export class ParentComponent {
@ViewChild('child') child: ChildComponent;
message: any;
The ChildComponent is equipped with a form containing a considerable amount of data. Additionally, it contains an object named user that must have the appropriate permissions in order to save the form.
Child Component
save() {
if (this.user.role <= 2) postFormDataToDb();
Within the parent component, when a navigation link is clicked to go away, the following method is invoked:
this.child.save();
An error is encountered stating that this.child is null. It appears that the ChildComponent is being created as a new instance with empty values, rather than as the existing one. Despite this, the form seems to exist in the DOM as one of the fields can still be inspected.
I've attempted various methods to address this issue, but all lead to a null error. I've experimented with using a shared MessageService and subscribing to its messages.
this.subManager = this.messageService.getMessage().subscribe(message => {
this.message = message;
console.log("message=",message);
});
this.sendMessage('save');
However, the message doesn't reach the button (no content is displayed in the div).
<div *ngIf="message" (click)="saveUsers()">{{message.text}}</div>
I've also attempted to specifically target the #saveBtn from the child form using ViewChild.
@ViewChild('saveBtn') saveBtn: ElementRef;
And then tried to trigger a click event using the following code in the parent component:
this.saveBtn.nativeElement.click();
However, an error is reported stating that this.saveBtn is null.
The link provided appears to be related to a similar question, but the solutions involve *ngIf directives which I'm not currently utilizing, with the exception of displaying the message.
What am I overlooking in this scenario?