簡體   English   中英

從父組件引用時,子組件值為 null

[英]Child component values are null when referenced from parent component

我有一個父組件和一個子組件。 子項有一個表單,如果用戶更改了它並嘗試通過單擊父項上的鏈接離開,則需要保存該表單。

家長

@Component({
  selector: 'parent',
  templateUrl: './parent.html',
  providers: [MessageService]    
})
export class ParentComponent {
  @ViewChild('child') child: ChildComponent;
  message: any;

ChildComponent 有一個表單,其中輸入了大量數據。 它還有一個名為 object 的用戶,該用戶必須具有保存表單的權限。

孩子

 save() {
   if (this.user.role <= 2) postFormDataToDb();

在父級中,當單擊鏈接離開時,它會調用

this.child.save();

我得到的錯誤是this.child是 null。我可能是錯的,但看起來 ChildComponent 是一個所有內容都是空的新實例,而不是現有實例。 然而,表單似乎在 DOM 中,因為我可以檢查其中一個字段並顯示出來。

我嘗試了幾種不同的方法,但都產生了 null 錯誤。 我試過使用共享的 MessageService 並訂閱它。

this.subManager = this.messageService.getMessage().subscribe(message => {
  this.message = message;
  console.log("message=",message);
});
this.sendMessage('save');

但消息永遠不會到達按鈕(div 中沒有顯示任何內容)。

<div *ngIf="message" (click)="saveUsers()">{{message.text}}</div>

我試過從子表單中只加載#saveBtn

@ViewChild('saveBtn') saveBtn: ElementRef;

然后點擊它

this.saveBtn.nativeElement.click();

來自父組件。 錯誤說 this.saveBtn 是 null。

提供的鏈接似乎是一個重復的問題,但解決方案涉及 *ngIf 我不使用它,除了顯示消息。

我錯過了什么?

我終於通過將id="saveBtn"添加到按鈕和

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

在 parent.ts 文件中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM