gpt4 book ai didi

angular 4 - 从父组件 html 调用子组件函数

转载 作者:行者123 更新时间:2023-12-04 02:01:00 26 4
gpt4 key购买 nike

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

像这样:

子组件:

export class childComponent {
private value: boolean;

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

父组件:

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

有什么办法可以做到吗?

最佳答案

你可以用 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();
}
}

关于angular 4 - 从父组件 html 调用子组件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47249079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com