簡體   English   中英

從“查看子級”組件(從子級到父級)獲取價值

[英]Get Value from View Child Component (from Child to Parent)

我將此代碼發送給了我的父母(profile.component.ts)

@ViewChild(QuestionComponent) questions: QuestionComponent;

然后console.log('questions'); 返回

在此處輸入圖片說明

我只想獲取下面紅色突出顯示框內的問題值。 我怎樣才能做到這一點?

您可以使用@ViewChild指令訪問父組件中的子組件數據。

在您的父組件中:

ParentClass implements OnInit{

  @ViewChild(QuestionComponent) questionComponent: QuestionComponent;

  ngOnInit() {
    this.getQuestions(); // you can call this function wherever you need it
                         // just, for example, I am calling it from ngOnInit
  }

  getQuestions() {
    if (questionComponent) {
      console.log(questionComponent.questions); // like this way we can access child component variables and functions in parent class
    }
  }
}

希望這會幫助你。

注意:僅當您只有一個QuestionComponent作為孩子時,此方法才有效

暫無
暫無

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

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