angular 4 - 来自父组件html

时间:2017-11-12 13:00:34

标签: angular angular2-directives

我需要从父组件html调用子组件函数。

类似的东西:

子组件:

export class childComponent {
  private value: boolean;

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

父组件:

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

任何想法怎么做?

2 个答案:

答案 0 :(得分:2)

您可以使用查看子项

执行此操作
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();
      }
    }

或者您也可以使用字符串

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

答案 1 :(得分:1)

您无法使用@input绑定方法。您可以使用@ViewChild

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

然后在父组件

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