我想将我的复选框绑定到查询参数。例如:我有:
http://localhost:4200/products?pageNumber=1&pageSize=16&lenscolor=1&lenscolor=2
页面加载后,必须检查具有适当 id(1 和 2)的颜色复选框。我想,最好的方法是通过 [checked],但不知道它是如何正确实现的。
.html
<div *ngFor="let lensColor of lensColors; let i = index">
<input id="lensColor{{lensColor.id}}" type="checkbox" name="lensColor" (change)="doLensColorsFilter($event, lensColor.id)">
<label>{{lensColor.uaName}}</label>
</div>
.ts
export class SidebarComponent implements OnInit {
lensColors: Color[];
searchedLensColors = new Array<number>();
constructor(private router: Router,
private route: ActivatedRoute,
private productsService: ProductsService) {
this.routeSubscription = route.params.subscribe(params => this.category = params.category);
this.querySubscription = route.queryParams.subscribe(
(queryParam: any) => {
this.searchedLensColors = queryParam.lenscolor;
}
);
}
ngOnInit() {
this.loadLensColors();
}
private loadLensColors() {
this.productsService.getLensColors().subscribe((data: Color[]) => {
this.lensColors = data;
});
}
private doLensColorsFilter(event, lensColorId) {
const isChecked = event.target.checked;
if (isChecked) {
this.searchedLensColors.push(lensColorId);
} else {
const index = this.searchedLensColors.findIndex(el => el === lensColorId);
this.searchedLensColors.splice(index, 1);
}
this.router.navigate(['/products'], {queryParams: {lenscolor: this.searchedLensColors}, queryParamsHandling: 'merge'});
}
}
我的镜头颜色:
[
{id: 1, name: "black", uaName: "Чорний"}
{id: 2, name: "white", uaName: "Білий"}
{id: 3, name: "yellow", uaName: "Жовтий"}
]