angular2 call function of parent component

前端 未结 4 843
有刺的猬
有刺的猬 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:47

    You can inject the parent component to the child component.

    For more details see
    - How do I inject a parent component into a child component?
    - Angular 2 child component refers to parent component This way you can ensure that thefunction() is only called when parent is a body.component.

    constructor(@Host() bodyComp: BodyComponent) {
    

    Otherwise using @Output() is preferred to communicate from child to parent.

    0 讨论(0)
  • 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:

    <app-child [myMethod]="myMethodFunc"></app-child>
    

    Child template

    @Component({ ... })
    export class ChildComponent {
    
        @Input() myMethod: Function;
    
        // here I can use this.myMethod() and it will call ParentComponent's myMethod()
    }
    
    0 讨论(0)
  • 2021-01-30 01:55

    Below is worked for me in latest

    Angular5

    class ChildComponent {
      @Output() myEvent = new EventEmitter<string>();
    
      callParent() {
        this.myEvent.emit('eventDesc');
      }
    }
    

    In ParentTemplate's template

    <child-component (myEvent)="anyParentMehtod($event)"
    
    0 讨论(0)
  • 2021-01-30 01:57

    I would create a custom event in the child component. Something like that:

    @Component({
      selector: 'child-comp',
      (...)
    })
    export class ChildComponent {
      @Output()
      uploaded = new EventEmitter<string>();
    
      uploadComplete() {
        this.uploaded.emit('complete');
      }
    

    Your parent component could register on this event

    @Component({
      template `
        <child-comp (uploaded)="someMethod($event)"></child-comp>
      `,
      directives: [ ChildComponent ]
    })
    export class ParentComponent {
      (...)
    
      someMethod(event) {
      }
    }
    

    Another way would be inject the parent component in the child one but they will be strongly linked together...

    0 讨论(0)
提交回复
热议问题