如何在 Angular 中添加多个同名查询参数?

问题描述 投票:0回答:1

有没有办法仅使用 HTML 表达式在 Angular 中添加多个同名的查询参数?

我正在我的应用程序中构建过滤器,需要将 URL 结构与 API 相匹配。

/users?tag=One&tag=Two
<a
      class="dropdown-item mx-2"
      role="button"
      *ngFor="let tag of tags"
      routerLink="./"
      [queryParams]="{ tag: tag }"
      [queryParamsHandling]="'merge'"
    >
      <input class="form-check-input" type="checkbox" [name]="tag" />
      {{ tag }}
    </a>

与不同名称合并时效果很好,但似乎在幕后以

set(name, value)
的形式工作,而不是
append(name, value)
模式来接受具有相同键名称的多个值。

这是我在 stackblitz = 中的示例= https://stackblitz.com/edit/angular-uwattp

angular router
1个回答
0
投票

您可以在计算参数后编写自定义点击和重定向:

import { Component } from '@angular/core';
import { ActivatedRoute, NavigationExtras, Router } from '@angular/router';
import { take } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
})
export class HomeComponent {
  tags = ['One', 'Two', 'Three'];
  sources = ['google.com', 'facebook.com', 'twitter.com'];

  constructor(
    private readonly route: ActivatedRoute,
    private readonly router: Router
  ) {}

  navigateWithTag(selectedTag: string) {
    this.route.queryParams.pipe(take(1)).subscribe((p) => {
      const tagParams = p.tag ? [...p.tag, selectedTag] : [selectedTag];

      const queryParams: NavigationExtras = {
        queryParams: { ...p, tag: tagParams },
      };

      this.router.navigate(['.'], queryParams);
    });
  }
}

在模板中:

<a
  class="dropdown-item mx-2"
  role="button"
  *ngFor="let tag of tags"
  (click)="navigateWithTag(tag)"
>
  <input class="form-check-input" type="checkbox" [name]="tag" />
  {{ tag }}
</a>
© www.soinside.com 2019 - 2024. All rights reserved.