angular ng-select: addItem() call is resulting in a duplicated NgOption

29 views Asked by At

What I need to implement is a select with the possibility to add a new option and get this new option selected.

What is here is a working example what I need: https://stackblitz.com/edit/ng-select-wp6dzy?file=app%2Fapp.component.ts

In my implementation I'm creating the new option in the backend, then once the option is created, I need to add it to the options and select it.

What is happening is that the new option is getting added twice.

This is what I have:

html

      <ng-select [items]="(authorOptions | async)" bindValue="id" bindLabel="name"
                 [selectOnTab]="true"
                 [formControl]="author" #ngSelectAuthor>
      </ng-select>

      <button type="button" mat-button
              (click)="openAddAuthor()">
        <mat-icon>add</mat-icon>
      </button>

ts

...
  @ViewChild('ngSelectAuthor') ngSelectAuthor!: NgSelectComponent;
...
  authorOptions!: Observable<OptionSimple[]>;
...
  ngOnInit(): void {
    //This will come from backend
    this.authorOptions = new BehaviorSubject([
      {id: 1, name: 'The Author'}
    ]);
  }
...
  openAddAuthor() {
    //AuthorCreateComponent returns the new option created when close() is called
    const addAuthorDialogRef = this.dialog.open(AuthorCreateComponent);

    //Once closed, I check for a new author, add it and select it, but the result is below
    addAuthorDialogRef.afterClosed()
      .subscribe({
        next: option => {
          console.log(option);
          if (option) {
            const addedOption = this.ngSelectAuthor.itemsList.addItem(option);
            this.ngSelectAuthor.select(addedOption);
            console.log(this.ngSelectAuthor.itemsList);
          }
        }
      });
  }

You can see the option is added and selected, but twice, even I verified setting a breakpoint in this line and is executed only once:

const addedOption = this.ngSelectAuthor.itemsList.addItem(option); The new option is added twice to the ng-select items list

Here is the code executed internally by the library, I don't see nothing weird: https://github.com/ng-select/ng-select/blob/b0be7233a29463623933dec625830f402c0d1974/src/ng-select/lib/items-list.ts#L113

Any idea of what could be causing this?

(I was about to cancel the publication of this question because for some minutes was working as expected, but then again started with this behavior, what makes it worse for me because I didn't change anything)

0

There are 0 answers