Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Children route parameter are not set with withComponentInputBinding

In an Angular 18 application I can not have children route parameter set.

I have a route defined as

export const routes: Routes = [
  { path: 'test',
    children: [
       { path: ':operation/:id', component: CrudComponent },
       { path: ':operation', component: CrudComponent},
       { path: '', component: CrudComponent }
    ], component: TestComponent},

and in app.config.ts

  export const appConfig: ApplicationConfig = {
   providers: [provideRouter(routes,  withComponentInputBinding()),

in test.component.html

<a [routerLink]="['/test']">no operation</a>-
<a [routerLink]="['/test','onlyoperation']">only operation</a>-
<a [routerLink]="[ '/test','operationNid','123']">operation and id</a>
   <hr/>operation={{operation}}   id={{id}}  

and in test.component.ts

  @Input() operation:string="";
  @Input() id:number=0;

I expected to see the values shown by "operation={{operation}} id={{id}}", but they remain blank.

If I define the following routes, it works as expected

export const routes: Routes = [
  { path: 'test/:operation/:id', component: TestComponent },
  { path: 'test/:operation', component: TestComponent },
  { path: 'test', component: TestComponent},

where am I wrong?

like image 433
user2959635 Avatar asked Jan 21 '26 22:01

user2959635


1 Answers

The @Input you define works when you set it directly on the route :operation/:id, so only then it has access to the input binding, else it doesn't.

You have to look for other methods to access these properties from the parent.

You can listen for route changes, then watch for the params change, this is what gets binded to @Input.

@Component({
  selector: 'app-test',
  standalone: true,
  imports: [RouterModule, CommonModule],
  template: `
    <a [routerLink]="['/test']">no operation</a>-
    <a [routerLink]="['/test','onlyoperation']">only operation</a>-
    <a [routerLink]="[ '/test','operationNid','123']">operation and id</a>
      <hr/>operation={{operation | json}}   id={{id | json}}  
      <hr/>
      <router-outlet/>
  `,
})
export class TestComponent {
  navigationSub!: Subscription;
  operation = '';
  id = 0;
  activateRoute = inject(ActivatedRoute);
  router = inject(Router);

  ngOnInit() {
    this.navigationSub = this.router.events
      .pipe(filter((e): e is NavigationEnd => e instanceof NavigationEnd))
      .subscribe((value) => {
        const { operation, id } =
          this.activateRoute?.snapshot.firstChild?.params || {};
        this.operation = operation;
        this.id = id;
      });
  }

  ngOnDestroy() {
    this.navigationSub.unsubscribe();
  }
}

Stackblitz Demo

like image 194
Naren Murali Avatar answered Jan 24 '26 16:01

Naren Murali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!