角度2.我可以同时使用ViewChild和@Input吗? [英] Angular2. Can I use ViewChild and @Input at the same time?

查看:95
本文介绍了角度2.我可以同时使用ViewChild和@Input吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些数据传输到子元素中并在其中运行功能.我使用 ViewChild 访问该功能.但是在子 childParam 中仍未定义.

I need to transfer some data into child element and run function in it. I use ViewChild for access to the function. But in child childParam still undefined.

父模板:

<my-modal #myModal [childParam]="parentParam"></my-modal>

父组件:

@ViewChild('myModal') myModal;
parentParam: any;

onSubmit(value: any){
  this.parentParam = value;
  this.myModal.modalShow();
}

子组件:

@Input() childParam: any;

modalShow(){
  console.log(this.childParam);
}

为什么未定义 childParam ?

什么更好:直接通过 ViewChild 更改 childParam :

What is better: change directly childParam by ViewChild:

this.myModal.childParam = 'test string';

或通过功能参数发送数据:

or send data through function parameters:

this.myModal.modalShow('test string');

推荐答案

onSubmit()中执行 this.parentParam = value; 时,Angular首先需要运行更改检测以使绑定得到更新.

When this.parentParam = value; is executed in onSubmit() then Angular first needs to run change detection for bindings to get updated.

事件处理程序完成后,Angular运行更改检测.您的情况是 onSubmit(),这意味着 childParam 将获得在之后 onSubmit之后传递的 value ()已执行.

Angular runs change detection when an event handler has completed. Which in your case is onSubmit() which means that childParam will get the value passed after onSubmit() was executed.

您可以做的是明确运行更改检测

What you could do is to run change detection explicitely

  constructor(private cdRef:ChangeDetectorRef) {}

  onSubmit(value: any){
    this.parentParam = value;
    this.cdRef.detectChanges(); 
    // here `value` is assigned to `childParam` 
    this.myModal.modalShow();
  }

柱塞示例

这篇关于角度2.我可以同时使用ViewChild和@Input吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆