Access extended component's method from its parent in Angular

28 views Asked by At

I'm building a dynamic wizard component in Angular. I want the component to be smart so that the user has no configuration to handle, all one has to do is to call the wizard from a component and provide its steps components like so:

<wizard>
    <wizard-step>
        <select-fruit></select-fruit>
    </wizard-step>
    <wizard-step>
        <quantity></quantity>
    </wizard-step>
</wizard>

I am using:

@ContentChildren(WizardFullPageStepComponent)
public stepComponents: QueryList<WizardFullPageStepComponent>;

To dynamically get the steps and initialize the wizard's logic.
The select-fruit and quantity components extend a generic component:

@Component({
    selector: "av-wizard-generic-step",
    template: ""
})
export abstract class WizardGenericStep {
    abstract isValid(): void;
}
@Component({
    selector: "select-fruit",
    template: "Nice fruit"
})
export class FruitStepComponent{
    public isValid(): void {
        console.log("is the fruit is valid")
    }
}

I would like to implement the logic in the wizard-step component to be able to call the extended implemented isValid() method (here from FruitStepComponent) so that depending on the current step shown, the expected method is called.

To keep the component as generic as possible, I do not want to refer to the extended components but only the generic one:

@Component({
    selector: "av-wizard-full-page-step",
    templateUrl: "./wizard-full-page-step.component.html"
})
export class WizardFullPageStepComponent implements AfterContentInit {
    @Input()
    public showStep: boolean = false;

    @ContentChild("content", { static: false })
    public wizardGenericStep: WizardGenericStep;

    ngAfterContentInit() {
        // here this.wizardGenericStep is undefined
    }
}

I have tried the previous solution, but the value is undefined. How can I accomplish this? Is there a components' tree injector I could use maybe? I would be good with an ugly solution, as the logic of the wizard component will be hidden from the used.

0

There are 0 answers