angular2 call function of parent component

前端 未结 4 845
有刺的猬
有刺的猬 2021-01-30 01:33

I have an app where I have an upload component where I can upload a file. It is embedded in the body.component.

On upload, it should use a function (e.g.

4条回答
  •  不思量自难忘°
    2021-01-30 01:50

    Solution without events involved.

    Suppose that I have a ChildComponent and from that I want to call the method myMethod() which belongs to ParentComponent (keeping the original parent's context).

    Parent Component class:

    @Component({ ... })
    export class ParentComponent {
    
        get myMethodFunc() {
            return this.myMethod.bind(this);
        }
    
        myMethod() {
             ...
        }
    }
    

    Parent template:

    
    

    Child template

    @Component({ ... })
    export class ChildComponent {
    
        @Input() myMethod: Function;
    
        // here I can use this.myMethod() and it will call ParentComponent's myMethod()
    }
    

提交回复
热议问题