【问题标题】:Angular 5 Child component exposes properties but not methodsAngular 5子组件公开属性但不公开方法
【发布时间】:2018-08-09 16:02:57
【问题描述】:

知道为什么我可以获取所有子组件属性但不能获取它的任何方法吗?

我需要在子组件上调用一个方法(不使用服务或 eventEmmiter)来验证它的状态并返回一个属性。

家长

@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})
export class MyParent {
    @ViewChild('childEl') childEl: PhoneInputComponent;

    getChildValue() {
        const value = this.childEl.getMyValue();
        console.log(value);
        console.log(this.childEl);
    }
}

儿童

@Component({
    selector: 'phoneinput',
    templateUrl: 'phoneinput.html'
})
export class PhoneInputComponent {

    private onKey = new Subject<string>();
    @Input() phone: string;
    private errorMessage: string;

    getMyValue() {
        return 'hello from child';
    }
}

console.log 值:

未定义

this.childEl 的控制台.log:

PhoneInputComponent{onKey{}:Subject{}, phone:null, errorMessage:null}

无法使getValue() 可用

【问题讨论】:

  • 请提供一个有效的stackblitz
  • @ViewChild(PhoneInputComponent) childEl: PhoneInputComponent;应该可以,这就是我使用它的方式。
  • 向我们展示包含PhoneInputComponent 的模板,以及调用getChildValue 的代码。

标签: javascript angular


【解决方案1】:

修改你的代码

@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})
export class MyParent {
    @ViewChild(PhoneInputComponent) childEl: PhoneInputComponent;

    getChildValue(){
        const value = this.childEl.getMyValue();
        console.log(value);
        console.log(this.childEl);

}

例如:https://stackblitz.com/edit/angular-v4qqtt

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2011-10-07
    相关资源
    最近更新 更多