Search code examples
angularangular2-directives

angular 4 - call child component function from parent component html


I need to call child component function from parent component html.

something like this:

child component:

export class childComponent {
  private value: boolean;

  @input()
  setValue(inputVal){
    this.value = inputVal;
  }
}

parent component:

<childComponent  [setValue] = "true"></childComponent>

Any ideas how can it be done?


Solution

  • You can do this with view child

    import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
    
        @Component({
          selector: 'child-cmp',
          template: '<p>child</p>'
        })
        class ChildCmp {
          doSomething() {}
        }
        @Component({
          selector: 'some-cmp',
          template: '<child-cmp></child-cmp>',
          directives: [ChildCmp]
        })
        class SomeCmp {
          @ViewChild(ChildCmp) child:ChildCmp;
          ngAfterViewInit() {
            // child is set
            this.child.doSomething();
          }
        }
    

    or you can also do with string

    import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
     @Component({
      selector: 'child-cmp',
      template: '<p>child</p>'
    })
    class ChildCmp {
      doSomething() {}
    }
    @Component({
      selector: 'some-cmp',
      template: '<child-cmp #child></child-cmp>',
      directives: [ChildCmp]
    })
    class SomeCmp {
      @ViewChild('child') child:ChildCmp;
      ngAfterViewInit() {
        // child is set
        this.child.doSomething();
      }
    }