使用 multiple 和 typeahead 将所选项目添加到 ng-select

elt*_*are 10 javascript rxjs angular-ngselect angular

我正在使用ng-select从远程加载的大列表中选择多个值,具体取决于用户在框中键入的内容。以下是我的要求:

  1. 动态添加的标签
  2. 已选择的值不显示下拉列表。它仅用于提前输入可用的、未选择的值。

以下是我目前遇到的问题:

  • 如果所选标签不是items列表的一部分,则不会显示。
  • 使用标签对象作为一个数组[(ngModel)]品牌ng-select把它像所有不存在的价值。ng-select似乎只在[(ngModel)]when 中使用 ID [mutiple]=true,而不是在when 中使用所选对象[multiple]=false
  • tagsInput$观察到的不被解雇,如果[isOpen]=false

我已经验证它tagsService运行正常。

目前来看:

<ng-select [items]="tags$ | async"
           bindValue="name"
           [loading]="tagsLoading"
           [typeahead]="tagsInput$"
           [multiple]="true"
           [isOpen]="tagsOpen"
           [searchFn]="filterSelectedTags"
           [(ngModel)]="selectedTagIds"></ng-select>
Run Code Online (Sandbox Code Playgroud)

电流控制器:

class TagFormComponent {

  public tags$: Observable<Tag[]>;
  public tagsLoading: boolean;
  public tagsInput$: Subject<string>;
  public tagsChanger$: Subject<Tag[]>;
  public selectedTags: Tag[];
  public selectedTagIds: number[];
  public tagsOpen: boolean;

  constructor(private tagService: TagService) {

    this.tagsInput$ = new Subject<string>();
    this.tagsChanger$ = new Subject<Tag[]>();
    this.tagsChanger$.subscribe( tags => {
      this.selectedTagIds = tags.map(t => t.id);
      this.selectedTags = tags;
    });
    this.tags$ = concat(
      this.tagsChanger$,
      this.tagsInput$.pipe(
        debounceTime(200),
        distinctUntilChanged(),
        tap( () => {
          this.tagsOpen = true;
          this.tagsLoading = true;
        }),
        switchMap(q => this.tagService.search(q).pipe(
          catchError( err => { this.tagsLoading = false; console.error(err); return of([] ); }),
          tap( () => this.tagsLoading = false)
        ))
      )
    );

    this.tagsChanger$.next(this.assetGroup.tags);
  }

  public matcher(a: any, b: any): boolean {
    return !!a && b && a.id === b.id;
  }

  public filterSelectedTags(_q: string, item: Tag) {
    return !this.selectedTagIds.includes(item.id);
  }

  public tagAdded() {
    this.tagsOpen = false;
  }
}
Run Code Online (Sandbox Code Playgroud)

小智 0

使用 ng-select 的内置“hideSelected”属性来隐藏已选择的项目。

至于“如果不属于项目列表,则不会显示所选标签”,看起来您必须预加载已选择的项目。它们应该始终添加到“项目”列表中。由于“hideSelected”,它们无论如何都不会显示在下拉列表中。因此,组件应该首先通过 ID 加载现有项目并将它们添加到“项目”列表中,然后组件必须根据预先输入加载项目并将它们添加到“项目”列表中。这样现有的项目将始终可用于 ng-select。