从“查看子级”组件(从子级到父级)获取价值

时间:2018-12-12 06:21:05

标签: angular

我将此代码发送给了我的父母(profile.component.ts)

@ViewChild(QuestionComponent) questions: QuestionComponent;

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

enter image description here

我只想获取下面红色突出显示框内的问题值。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以使用@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作为孩子时,这才有效

相关问题