Search code examples
angularangular-componentsangular2-ngcontent

Access parent component from child component when parent component using ng-content Angular


I'm trying to access parent component from child component using dependence injection. It works, I can access to parent to using its methods and properties but I have not seen this approach on Angular doc. So do you have any idea about this approach? Should I use it?

Because the parent component using ng-content (like transclude angularjs) so I cannot using EventEmitter @Output approach.

The bellow is my code:

wizard.component.ts (parent)

import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'wizard',
    template: `
        <div>
            <ng-content></ng-content>
            <button>Back</button>
            <button>Next</button>
        </div>
    `
})
export class WizardComponent implements OnInit {
    steps = [];

    constructor() { }

    addStep(step) {
        this.steps.push(step);
    }

    ngOnInit() { }
}

step.component.ts (child)

import { WizardComponent } from './wizard.component';
import { Component, OnInit } from '@angular/core';

@Component({
    selector: 'step',
    template: `
        <div>Step <ng-content></ng-content></div>
    `
})
export class StepComponent implements OnInit {
    constructor(private parent: WizardComponent) { 
        this.parent.addStep(this);
    }

    ngOnInit() { }
}

app.component.html (main app)

<wizard>
    <step>1</step>
    <step>2</step>
    <step>3</step>
</wizard>

Looking forward to hearing your opinions. Thanks!


Solution

  • Finally I found the document about parent dependence injection here https://angular.io/docs/ts/latest/cookbook/dependency-injection.html#!#known-parent.

    And there is an article that using it: https://blog.thoughtram.io/angular/2015/04/09/developing-a-tabs-component-in-angular-2.html

    Hope it will help someone who has the same concern like me.