0

嘿,我尝试学习 @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

4

1 回答 1

2

您可以使用类似的@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>
于 2021-04-13T09:54:24.703 回答