withComponentInputBinding作用

39 阅读1分钟
  • 将路由参数(路径参数、查询参数、矩阵参数等)自动映射到组件的 @Input() 属性。
  • 无需手动通过 ActivatedRoute 订阅参数变化,简化代码。

传统方式 vs 输入绑定

传统方式(手动订阅参数)
// 组件代码
import { ActivatedRoute } from '@angular/router';

export class ProductComponent {
  productId!: string;

  constructor(private route: ActivatedRoute) {
    this.route.params.subscribe(params => {
      this.productId = params['id']; // 手动获取参数
    });
  }
}
输入绑定方式(自动映射)
// 组件代码
export class ProductComponent {
  @Input() id!: string; // 自动接收路由参数 id
}

路由配置示例

// 路由定义
const routes: Routes = [
  {
    path: 'products/:id',
    component: ProductComponent
  }
];

支持的参数类型

参数类型示例 URL组件输入属性
路径参数/products/123@Input() id: string
查询参数/products?category=books@Input() category: string
矩阵参数/products;view=grid@Input() view: string

配置示例

// app.config.ts
import { provideRouter, withComponentInputBinding } from '@angular/router';

export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(
      routes,
      withComponentInputBinding() // ⭐ 启用输入绑定
    )
  ]
};