angular how to refresh the value of @Input

1k views Asked by At

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

1

There are 1 answers

0
Michael D On BEST ANSWER

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>