I want to bind my checkboxes to query parameters. For example: I have:
http://localhost:4200/products?pageNumber=1&pageSize=16&lenscolor=1&lenscolor=2
And after page loading, my colors checkboxes with appropriate id (1 and 2) must be checked. I guess, that the best way is via [checked], but don't know how it implement correctly.
.html
<div *ngFor="let lensColor of lensColors; let i = index">
<input id="lensColor" type="checkbox" name="lensColor" (change)="doLensColorsFilter($event, lensColor.id)">
<label></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'});
}
}
my lensColors:
[
{id: 1, name: "black", uaName: "Чорний"}
{id: 2, name: "white", uaName: "Білий"}
{id: 3, name: "yellow", uaName: "Жовтий"}
]
Aucun commentaire:
Enregistrer un commentaire