Injection fails when the action is triggered from a child component

Discussão em 'Angular' iniciado por perissf, Dezembro 8, 2024.

  1. perissf

    perissf Guest

    Learning Angular 18, I am facing an unexpected behaviour: injection silently failing when an action is triggered by a child component, but ultimately it's defined in the parent component, where the injection fails.

    child.component.ts

    @Component({
    selector: 'app-child',
    standalone: true,
    imports: [],
    template: `
    <button type="button" (click)="action()">Navigate using child</button>
    `,
    styles: ``
    })
    export class ChildComponent {
    @Input() action: () => void = () => {};
    }


    parent.component.ts

    import { Component, inject } from '@angular/core';
    import { ChildComponent } from "../child/child.component";
    import { Router } from '@angular/router';

    @Component({
    selector: 'app-parent',
    standalone: true,
    imports: [ChildComponent],
    template: `
    <h1>Parent</h1>
    <app-child [action]="actionInParent" />
    <button type="button" (click)="actionInParent()">Navigate using parent</button>
    `,
    styles: ``
    })
    export class ParentComponent {
    private router = inject(Router)

    actionInParent() {
    console.log("Action invoked")
    this.router.navigateByUrl('child')
    }

    }


    If I press "Navigate using parent", navigation works. If I press "Navigate using child", navigation fails (in the console I see an error triggered by router being undefined).

    Continue reading...

Compartilhe esta Página