Search code examples
angularinputangular-input

angular how to refresh the value of @Input


Hey i try to learn @Input to minimize redundant code.

My Problem is the i dont now how to get my list updatet

Component that receives data

    export class DumpListComponent implements OnInit {
    @Input() dataSource: MatTableDataSource<Book>;

    openCreateBookDialog(): void {
      const dialogRef = this.dialog.open(CreateBookDialogComponent, {
      width: '360px'
    });
    dialogRef.afterClosed().subscribe(response => {
      if (response) {
        this.getBooks();
      }
    });
  }
}

I am importing the datasource from a other component and in this component is a methode to update the datasource

Component that sends the data

  export class ViewListComponent implements OnInit {

  dataSource = new MatTableDataSource();

  constructor(private bookService: BookService, private keycloakService: KeycloakService) {

    bookService.getListOfAllBooks().subscribe(books => {
      this.dataSource = new MatTableDataSource(books);
    });

  }

  ngOnInit(): void {
  }

  getBooks(): void {
    this.bookService.getListOfAllBooks().subscribe(books => {
      this.dataSource = new MatTableDataSource(books);
    });
  }

Injecting the dataSource

<app-dump-list [dataSource]="dataSource"></app-dump-list>

Does anyone know how I can call this method from the other component so that the datasource is updated?

Thx for your time

Solution https://angular.io/guide/inputs-outputs#sending-data-to-a-parent-component


Solution

  • You could use an analogous @Output variable to emit custom events from the child component to the parent.

    Child

    import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
    
    export class DumpListComponent implements OnInit {
      @Input() dataSource: MatTableDataSource<Book>;
      @Output() getBooks = new EventEmitter<any>();
    
      openCreateBookDialog(): void {
        const dialogRef = this.dialog.open(CreateBookDialogComponent, {
          width: '360px'
        });
    
        dialogRef.afterClosed().subscribe(response => {
          if (response) {
            this.getBooks.emit();
          }
        });
      }
    }
    

    Parent (*.html)

    <app-dump-list [dataSource]="dataSource" (getBooks)="getBooks()"></app-dump-list>