angular 4 - 从父组件调用子组件函数html
angular 4 - call child component function from parent component html
我需要从父组件调用子组件函数html。
像这样:
子组件:
export class childComponent {
private value: boolean;
@input()
setValue(inputVal){
this.value = inputVal;
}
}
父组件:
<childComponent [setValue] = "true"></childComponent>
有什么办法可以做到吗?
您不能使用@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);
}
}
您可以使用 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();
}
}
或者您也可以使用字符串
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();
}
}
我需要从父组件调用子组件函数html。
像这样:
子组件:
export class childComponent {
private value: boolean;
@input()
setValue(inputVal){
this.value = inputVal;
}
}
父组件:
<childComponent [setValue] = "true"></childComponent>
有什么办法可以做到吗?
您不能使用@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);
}
}
您可以使用 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();
}
}
或者您也可以使用字符串
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();
}
}