Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 : how to call main component function from a child component

How to call main component function from a child component when I have deep nested hierarchy?

enter image description here

I have 3 components, button component I'm including inside browser component and browser component I'm including inside main component.

On click of button I need to call a function which is inside main component.

Button Component

@Component({
    selector: 'cb-button',
    templateUrl: 'cb-button.component.html',
    styleUrls: ['cb-button.component.scss']
})

export class CbButtonComponent {

     @Output() onClick: EventEmitter<any> = new EventEmitter();

     onBtnClick(): void {
        this.onClick.emit();
    }
}

button component html

<div (click)="onBtnClick()">
    <button>btn</button>
</div>

browser component

@Component({
    selector: 'topology-browser',
    templateUrl: 'topology-browser.component.html',
    styleUrls: ['topology-browser.component.scss']
})

export class TopologyBrowserComponent {

   @Input('campus') campus: Campus;
}

browser component html

<div>
<h1>browser title</h1>
<cb-button (click)="editCampus()"></cb-button>
</div>

and finally in main component i'm including browser component

main-component.ts

editCampus() {
  alert('clicked');
}

html

<topology-browser [campus]="campus"></topology-browser>

when I click button I'm getting below error

Errorself.parentView.context.editCampus is not a function

like image 735
Pratap A.K Avatar asked Aug 07 '26 14:08

Pratap A.K


1 Answers

  • If you know what type the root component is, you can use Pengyy's method.
  • If you don't know what type in advance but you can customize the root component to your needs, a shared service is a good way.

  • A more generic way is to get the root component by injecting ApplicationRef (not actually tested myself):

constructor(app:ApplicationRef, injector: Injector) {
  app.components[0].someMethodOnMainComponent();
}

https://angular.io/docs/ts/latest/api/core/index/ApplicationRef-class.html

like image 105
Günter Zöchbauer Avatar answered Aug 09 '26 02:08

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!