Angular2。我可以同时使用ViewChild和@Input吗?

时间:2017-02-16 12:40:48

标签: angular

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

父模板:

<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未定义?

更好的方法是:childParam直接更改ViewChild

this.myModal.childParam = 'test string';

或通过函数参数发送数据:

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

2 个答案:

答案 0 :(得分:0)

您不需要通过@ViewChild引用设置子参数。

试试这个。父模板:

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

父组件:

private parentParam: any;

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

parentParam的值将以这种方式直接绑定到childParam值,因此每当更新parentParam值时,它将在子组件中可用。

如果这不起作用,那么尝试将ngOnChanges添加到子组件,因为无论何时从父组件更新值,您都可以调试(设置断点):

导入OnChanges(除了@ angular / core中的其他导入外,还要添加它):

import { OnChanges} from '@angular/core';

将NgOnChanges添加到子组件类:

export class MyChildComponent implements OnChanges {

实施方法ngOnChanges。只要输入参数发生更改,就会调用此方法:

 ngOnChanges(changes: any) {
     debugger; //set breakpoint
 }

答案 1 :(得分:0)

this.parentParam = value;中执行onSubmit()时,Angular首先需要对绑定进行更改检测才能获得更新。

当事件处理程序完成时,Angular运行会更改检测。在您的情况下onSubmit(),这意味着childParam会在 value执行后onSubmit()通过

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

  constructor(private cdRef:ChangeDetectorRef) {}

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

Plunker example