首页 文章

从Angular中的子组件调用父组件函数[关闭]

提问于
浏览
4

我试图调用我的 close() 函数,该函数位于Angular中子组件的父组件中 .

这是我在Plunker上的代码,我试图导入组件并直接在我的子组件中调用该函数但是我收到此错误:无法读取属性'close' of undefined

我怎样才能解决这个问题?

1 回答

  • 21

    我将尝试对您可能遇到的两种情况给出完整的答案:

    Case 1: Calling a child function from the parent component

    您可以通过在子选择器上使用模板变量来引用父组件模板中的子组件,然后使用该引用调用任何公共函数或属性来实现此目的 .

    所以在你的子组件中,你有一个功能:

    test(){
        console.log(`this is a test`);
    }
    

    并且在您的父组件中,您可以在父组件中调用它,让我们说按下按钮后就像这样:

    <child-component #childRef></child-component>
    <button (click)="childRef.test()">
        Call the child test function
    </button>
    

    Case 2: Calling a parent function from the child component

    这是一个由您的用例决定的情况,因为您可以在子组件中注入父组件并执行与上面相同的操作,但关系不再是父子组件或子组件父组件,但两个组件将强烈链接在一起是一个罕见的用例 . 或者,您可以通过使用 @Output 装饰器传递数据并在您的孩子中创建将消耗传入数据的函数,以非常简单的方式获得相同的结果 .

    所以在您的子组件中,您执行以下操作:

    @Output() childEvent = new EventEmitter();
    test(){
        this.childEvent.emit('this is a test');
    }
    

    在您的父模板中

    <child-component (childEvent)="test($event)"></child-component>
    

    然后在你的组件中

    test(msg){
        console.log(msg);
    }
    

相关问题