-1

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?

user3217883
  • 1,216
  • 4
  • 38
  • 65
  • Does this answer your question? [Angular 2 @ViewChild annotation returns undefined](https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined) – GJohannes Apr 14 '22 at 22:34
  • the child component is rendering in dom when you call the save method? – Lautaro Lopez Ruiz Apr 14 '22 at 22:44
  • Yes. The parent component is a navigation menu on the left and the child component is on the right, completely rendered and filled with data. – user3217883 Apr 14 '22 at 22:46
  • The link seems to deal with *ngIf causing the problem. I'm not using those. My guess is that @ViewChild is referencing an empty ChildComponent when ParentComponent is created. Later when ChildComponent gets instantiated, ParentComponent still points to the empty one. – user3217883 Apr 14 '22 at 23:11

1 Answers1

0

I finally got it to work using conventional javascript way by adding id="saveBtn" to button and

document.getElementById('saveBtn').click();

in the parent.ts file.

user3217883
  • 1,216
  • 4
  • 38
  • 65