Angular child routes not reloading the component

Discussão em 'Angular' iniciado por Ziz, Agosto 2, 2025.

  1. Ziz

    Ziz Guest

    I'm trying to write a very basic calorie couting app, however I've run into an issue with child routing in Angular.

    I have a list of child routes selectable from a list that should route to a child component on the page for details about the ingredient selected. This works the first time you select a link, however it stops working if there is aleady a child component loaded, even when the route changes.

    app.routes.ts

    export const routes: Routes = [
    ...
    {
    path: 'ingredients',
    component: Ingredients,
    title: 'Ingredients',
    children: [
    {
    path: ':id',
    component: IngredientComponent,
    }
    ]
    },
    ...
    { path: '**', redirectTo: 'dashboard'}


    ];

    ingredients.html

    ...
    <div class="col">
    <button type="button" class="btn btn-primary position-relative">Add Ingredient</button>
    </div>
    </div>
    <div class="list-group">
    @for (ingredient of ingredients; track ingredient.id) {
    <a class="list-group-item" [routerLink]="[ingredient.id]">{{ingredient.name}}</a>
    }
    @empty {
    <div class="list-group-item">There are no ingredients currently stored</div>
    }
    </div>

    </div>
    <div class="col-8">
    <router-outlet />
    </div>


    IngredientComponent

    export class IngredientComponent {
    id:number
    ingredient: Ingredient | undefined;

    constructor(private IngredientService: IngredientService, private route: ActivatedRoute){
    this.id = Number(this.route.snapshot.params['id']);
    this.ingredient = this.IngredientService.getIngredient(this.id)
    }

    ngOnInit(){
    console.log('init\'d component')
    }

    ngOnDestroy() {
    console.log('Destroying component')
    }
    }


    Working stackblitz example here

    Continue reading...

Compartilhe esta Página