【问题标题】:How to make checkbox checked from the query parameters?如何从查询参数中选中复选框?
【发布时间】:2019-08-23 06:04:40
【问题描述】:

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

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

【问题讨论】:

    标签: angular checkbox checked query-parameters angular-activatedroute


    【解决方案1】:

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

    第一个

     <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)">
    

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

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2021-10-07
      • 2021-09-18
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-10
      • 2014-10-18
      相关资源
      最近更新 更多