Shay
Shay

Reputation: 407

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?

Upvotes: 3

Views: 4376

Answers (2)

Karty
Karty

Reputation: 1399

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

Upvotes: 3

Sajeetharan
Sajeetharan

Reputation: 222652

You can't bind a method using @input. You can do this by using @ViewChild

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class childComponent {
   value : anyl
   setValue(inputVal){
     this.value = inputVal;
  }
}

and then in parent component

class SomeCmp {
  @ViewChild(ChildCmp) child:ChildCmp;
  ngAfterViewInit() {
    this.child.setValue(yourval);
  }
}

Upvotes: 1

Related Questions