嘿,我试着学习@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-数据对板组件
您可以使用类似的@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>