【问题标题】:angular how to refresh the value of @Input角度如何刷新@Input的值
【发布时间】:2021-07-08 08:49:13
【问题描述】:

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

【问题讨论】:

    标签: angular input angular-input


    【解决方案1】:

    您可以使用类似的 @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>
    

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 2019-02-18
      • 1970-01-01
      • 2013-12-15
      • 2020-01-02
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多