简体   繁体   中英

Lose input focus when emitting an event Angular 5?

I am using angular 5 + ngrx/store. I have own tokenfield component. That should work exactly like bootstrap-tokenfield . It look something like this stackblitz . In stackblitz it works as expected, but in my app for some reasons i lose focus after every token added. It seems like pressEnter event trigger lose focus. pressEnter triggers an action in the container:

addToken(token: Token) { this.store.dispatch(new Actions.addToken(token)); }

And then i am passing to the component throw the container tokens:

[tokens]="tokens$ | async"

And here is the function in the reducer that handle this action:

export function addTokenCase(payload: Token, state: State) {
  return state.map((tokenModel) => {
    if (tokenModel.from === payload.from) {
      return {
        ...tokenModel,
        items: uniqueArray<string>([...tokenModel.items, ...payload.tokens]),
      };
    }
    return tokenModel;
  });
}

Where uniqueArray is :

export function uniqueArray<T>(array: T[]): T[] {
  return array.filter((elem, pos, arr) => arr.indexOf(elem) === pos);
}

What can be the problem? Thank you.

I found what was the source of the problem. I had *ngFor above tokenfield component:

<div *ngFor="let token of tokens">
  <ui-token [token]="token"></ui-token>
</div>

So when i changed state with .map() - all <ui-token /> components were rerendered. I added trackBy and it works now as expected without rerendering:

<div *ngFor="let token of tokens; trackBy: trackToken">
  <ui-token [token]="token"></ui-token>
</div>

Where trackToken is:

trackToken(index: number) {
  return index;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM