简体   繁体   English

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

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

I have this code to my parent (profile.component.ts) 我将此代码发送给了我的父母(profile.component.ts)

@ViewChild(QuestionComponent) questions: QuestionComponent;

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

在此处输入图片说明

I just want to get the questions value which the red highlighted box below . 我只想获取下面红色突出显示框内的问题值。 How can I do this? 我怎样才能做到这一点?

You can access the child component data in parent component using @ViewChild directive. 您可以使用@ViewChild指令访问父组件中的子组件数据。

In your parent component: 在您的父组件中:

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
    }
  }
}

Hope this will help you. 希望这会帮助你。

Note: This will work only if you are having only one QuestionComponent as a child 注意:仅当您只有一个QuestionComponent作为孩子时,此方法才有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM