简体   繁体   中英

Angular2. Can I use ViewChild and @Input at the same time?

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.

Parent template:

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

Parent component:

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

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

Child component:

@Input() childParam: any;

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

Why childParam is undefined?

What is better: change directly childParam by ViewChild :

this.myModal.childParam = 'test string';

or send data through function parameters:

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

You don't need to set the child parameter through a @ViewChild reference.

Try this instead. Parent template:

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

Parent component:

private parentParam: any;

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

The value of parentParam will bind to the childParam value directly in this way so whenever the parentParam value is updated it will be available in the child component.

If that does not work then try and add ngOnChanges to the child component since you will then be able to debug (set a breakpoint) for whenever the value is updated from the parent:

Import OnChanges (add this in addition to the other imports you have from @angular/core):

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

Add NgOnChanges to your child component class:

export class MyChildComponent implements OnChanges {

Implement method ngOnChanges. This method will be called whenever an input parameter is changed:

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

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

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();
  }

Plunker example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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