angularrouter-outlet

Angular 14 - Send a parameter that is an object to the router-outlet directive


I have the following component template: users.component.html:

<app-user-card class="card-container" *ngIf="user" [user]="user"></app-user-card>
<div>
  <router-outlet *ngIf="user"></router-outlet>
</div>

User is an object like this:

this.user = {
  id: 1,
  name: "Jonh",
  icon: "jonhn.svg",
  subsusers: [],
}

I need to pass the "User" object to the "router-outlet" and receive it on all components used in that routes.

What is the best way to do this?


Solution

  • For v16 the solution would probably be to rely on input bindings combined with the resolver :

    provideRouter(
          [
            {
              path: 'todos/:todoId',
              data: {
                isSomething: true, 
              },
              resolve: { resolveFoo: () => 'My resolved data' },
              component: TodoComponent,
            },
          ],
          withComponentInputBinding() // to enable input bindings
        ),
    

    The component with the binded inputs:

    @Component({
      ...
      standalone: true,
    })
    export default class TodoComponent {
      @Input() resolveFoo: string; // My resolved data
      @Input() isSomething: boolean; // true
      @Input() todoId: string; // 1
    }
    

    Since you are "stucked" on v14, you should probably share the data through a provided service between the components.