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

标签 angular

我需要将一些数据传输到子元素中并在其中运行函数。 我使用 ViewChild 来访问函数。但是在 child 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 是未定义的?

更好的是:ViewChild直接改变childParam:

this.myModal.childParam = 'test string';

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

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

最佳答案

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

Angular 在事件处理程序完成时运行更改检测。在你的情况下是 onSubmit() 这意味着 childParam 将获得 value after 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

关于 Angular 2。我可以同时使用 ViewChild 和 @Input 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274276/

相关文章:

Angular 2 groupby或过滤管道

angular - 无法在 Angular 2 中的 *ngFor 中找到变量

javascript - 对于 NodeJs Promise,Await 和 Then 哪个更好?以及等待如何工作

angular - Material 单选按钮更改事件Angular 4

javascript - Ionic 3 多页面功能模块

javascript - 使用 ngFor 在特定布局中渲染表格

angular - 如何更改 ngb 分页背景颜色

typescript - 转译 Angular2 TS 时如何配置 gulp-typescript 以与 JSPM 一起工作

javascript - this.httpClientModule.get 不是函数

javascript - Angular 4 div hidden vs ngIf render Agm Google Map API