Search code examples
angularfocusdatasourceangular-material-table

After updating MatTableDataSource focus disappears angular


After updating the input element in one row and clicking on the input in the next row, the focus disappears because the datasource gets updated. Is there any way to preserve focus while updating datasource? I have spent a lot of time on it. If someone knows how it can be solved let me know. Thanks.

focusedIn(event: Event, article: ArticleDef): void {
    this.activeArticle = article;
    this.facade.active(article.id);
    (event.target as HTMLInputElement).focus();
}

 ngOnChanges(changes: SimpleChanges): void {
    if (changes.articles) {
    this.dataSource = new MatTableDataSource<ArticleDef & Selectable>(changes.articles.currentValue);
    }
}

  changeQuantity(event: Event, article: ArticleDef): void {
    this.quantityChange.emit({
      id: article.id,
      name: article.name,
      quantity: parseInt((event.target as HTMLInputElement).value)
    });
  }

Solution

  • It can be done as follow:

    focusedIn(event: Event, article: ArticleDef): void {
        this.activeArticle = article;
        this.returnArticlesFacade.active(article.id);
        setTimeout(() => {
          (event.target as HTMLInputElement).focus();
        }, 0);
     }
     
     ngOnChanges(changes: SimpleChanges): void {
     if (changes.articles) {
        this.dataSource = new MatTableDataSource<ArticleDef & Selectable>(changes.articles.currentValue);
    
       // Here you can change if condition according to your requirement
       if (this.activeArticle) {
          setTimeout(() => {
            //WE are passing this.activeArticle.id by assuming that it is the id of the element. If it is not then change it according to your requirement
            const element = document.getElementById(this.activeArticle.id).getElementsByTagName('input')[0];
            element.focus();
          }, 0);
       }
     }