ngaotruyen
ngaotruyen

Reputation: 63

Angular 17 params null from child component and app root

I use Angular 17 and SSR.

when router: en/home/1. I add inject(ActivatedRoute). But i can't get the params from the child component or the app root component. how to get params from component child (app-menu)

after code:

app.routes.ts

export const routes: Routes = [
  { path: ":lang/home/:id", component: HomeComponent },
];

app.config.ts

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withComponentInputBinding(),
      withRouterConfig({ paramsInheritanceStrategy: 'always' })
    ),
    provideClientHydration(),
    provideHttpClient(withFetch()),
  ],
};

app.component.ts

 constructor(
    private translocoService: TranslocoService,
    @Inject(ActivatedRoute)private routeActive: ActivatedRoute,
    @Inject(DOCUMENT) private document: Document
  ) {
console.log(this.activatedRoute.snapshot.params['id']);

}

app.component.html

  <div class="layout-wrapper layout-navbar-full layout-horizontal layout-without-menu">
      <div class="layout-container">
        <app-menu></app-menu>
            <router-outlet></router-outlet>
          </div>
        </div>
      </div>
    </div>

app-menu.component.ts:

@Component({
  standalone: true,
  imports:[CommonModule, HorizontalMenuComponent, VerticalMenuComponent],
  selector: 'app-menu',
  templateUrl: './menu.component.html',
})
export class MenuComponent implements OnInit {
  private activatedRoute = inject(ActivatedRoute);

constructor (private router : Router){
console.log(this.activatedRoute.snapshot.params['id']);
}

Upvotes: 0

Views: 1941

Answers (2)

anousss
anousss

Reputation: 357

When you call activatedRoute.snapshot.params you get the URL Params of the current URL. If you want to get the params of child components you need to use firstChild :

this.activatedRoute.firstChild?.snapshot.paramMap.get('childId')

You could go further and call firstChild.firstChild.params

Upvotes: 1

Fabian Lain&#233;
Fabian Lain&#233;

Reputation: 19

To access route params from anywhere (app component or child components) you can add activatedRoute dependency on the constructor and subscribe to params :

constructor(private activatedRoute: ActivatedRoute){
    this.activatedRoute.params.subscribe(params=>{
        console.log(params?.['id']);
        // You logic
    });
}

Upvotes: 0

Related Questions