角度如何刷新@Input的值

问题描述

嘿,我尝试学习@Input 以尽量减少冗余代码

我的问题是我现在不知道如何更新我的列表

接收数据的组件

    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();
      }
    });
  }
}

我正在从其他组件导入数据源,并且在该组件中是更新数据源的方法

发送数据的组件

  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);
    });
  }

注入数据源

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

有谁知道我如何从另一个组件调用这个方法来更新数据源?

感谢您的时间

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

解决方法

您可以使用类似的 @Output 变量从子组件向父组件发出自定义事件。

儿童

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();
      }
    });
  }
}

父级 (*.html)

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