0

我想将我的复选框绑定到查询参数。例如:我有:

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: "Жовтий"}
]
4

1 回答 1

0

我的英语很差,但有几种方法。

首先

 <input id="lensColor{{lensColor.id}}" [checked]="lensColor.checked" type="checkbox" name="lensColor" (change)="doLensColorsFilter($event, lensColor.id)">

第二

  <input id="lensColor{{lensColor.id}}" [(ngModel)]="lensColor.checked" type="checkbox" name="lensColor" (change)="doLensColorsFilter($event, lensColor.id)">

在展位情况下,您必须在数组中创建此字段,如果包含信息检查为真。

我希望能有所帮助。

于 2019-08-22T22:04:40.073 回答