[英]Child component values are null when referenced from parent component
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. ChildComponent 有一个表单,其中输入了大量数据。 It also has an object called user which must have permission to save the form.它还有一个名为 object 的用户,该用户必须具有保存表单的权限。
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.我得到的错误是this.child是 null。我可能是错的,但看起来 ChildComponent 是一个所有内容都是空的新实例,而不是现有实例。 Yet it seems like the form is in the DOM since I can inspect one of the fields and it shows up.然而,表单似乎在 DOM 中,因为我可以检查其中一个字段并显示出来。
I've tried several different approaches but all produce a null error.我尝试了几种不同的方法,但都产生了 null 错误。 I've tried using a shared MessageService and subscribing to it.我试过使用共享的 MessageService 并订阅它。
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 中没有显示任何内容)。
<div *ngIf="message" (click)="saveUsers()">{{message.text}}</div>
I've tried loading just the #saveBtn from the child form我试过从子表单中只加载#saveBtn
@ViewChild('saveBtn') saveBtn: ElementRef;
and clicking it with然后点击它
this.saveBtn.nativeElement.click();
from the parent component.来自父组件。 Error says this.saveBtn is null.错误说 this.saveBtn 是 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.提供的链接似乎是一个重复的问题,但解决方案涉及 *ngIf 我不使用它,除了显示消息。
What am I missing?我错过了什么?
I finally got it to work using conventional javascript way by adding id="saveBtn"
to button and我终于通过将id="saveBtn"
添加到按钮和
document.getElementById('saveBtn').click();
in the parent.ts file.在 parent.ts 文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.