Search code examples
methodsangularcomponentsparentchildren

Angular2 access to the methods in child component from parent


My question is about the way of have access to childerns component methods from parent component. I found solution which is describe using below example, but I afraid that may be I do it in wrong, not 'angular2 right' way.

For instance we have child:

@Component({ ... })
export class Modal {
    ...
    open() {
        ...
    }
}

And parent:

import { Modal } from '../common';
...
@Component({
  selector: 'editor',
  directives: [ Modal ],
  templateUrl: './editor.html',
  ...
})
export class Editor {

    _modal = null;

    ...

    bindModal(modal) { this._modal=modal; }

    open() {
        this._modal.open();
    }
}

And in editor.html:

<button (click)="open()">Open Editor</button>

<modal #editModal>{{ bindModal(editModal) }}
    Here is my editor body in modal (popup) window
    ...
</modal>

This is solution for have access from Editor component to the open() method inside Modal component. It is a little bit tricky. The question is: is there a simplest and more direct way without using 'bindModal' method?


Solution

  • There are many ways to do it,

    @ViewChild

    import  {ViewChild} from '@angular/core';
    import { Modal } from '../common';
    ...
    @Component({
      selector: 'editor',
      directives: [ Modal ],
      templateUrl: './editor.html',
      ...
    })
    export class Editor {
     @ViewChild(Modal) md:Modal;
    
     Open()
     {
        this.md.open();
     }
    
    }
    

    Other way is to use #localVariable and from parent itself you can access child methods.