【问题标题】:Angular2. Can I use ViewChild and @Input at the same time?角2。我可以同时使用 ViewChild 和 @Input 吗?
【发布时间】:2017-02-16 12:40:48
【问题描述】:

我需要将一些数据传输到子元素并在其中运行函数。 我使用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');

【问题讨论】:

  • 我猜parentParam 在调用modalShow() 时尚未设置,但很难说,因为代码不允许推导出可能发生的事情。
  • 我创建了 plunker link。当我第一次单击按钮时 - 没有显示任何内容,第二次单击时 - 显示了字符串。

标签: angular


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    试试这个。父模板:

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

    父组件:

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

    parentParam 的值将通过这种方式直接绑定到 childParam 值,因此无论何时更新 parentParam 值,它都会在子组件中可用。

    如果这不起作用,请尝试将 ngOnChanges 添加到子组件,因为这样您就可以在从父组件更新值时进行调试(设置断点):

    Import OnChanges(除了您从 @angular/core 获得的其他导入之外,还添加这个):

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

    将 NgOnChanges 添加到您的子组件类中:

    export class MyChildComponent implements OnChanges {
    

    实现方法 ngOnChanges。每当更改输入参数时都会调用此方法:

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

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2013-10-09
      • 2020-06-04
      • 2011-07-21
      • 2015-05-19
      • 2019-05-21
      • 2021-09-05
      • 2014-04-08
      • 2020-06-23
      相关资源
      最近更新 更多