angular - 添加新行后角度垫表不刷新
问题描述
(角度 8)
我有两个组件 addgame 和 home,在 home 中,我在 REST API 的帮助下显示了存储在数据库中的所有游戏。
在 home 组件中,通过使用 Mat-dialog,我在对话框视图中调用了游戏组件。
问题是如果我在那个垫子对话框中添加了游戏,它会成功添加但是只有在手动刷新主页组件之后才会在垫子表中更新
我需要没有任何手动刷新的 mat-table 更新
注意:我尝试 了ChangeDetectorRef,触发了MatPaginator和所有可能的答案,但没有变化
home.component.html
<div class="search-div">
<button mat-raised-button (click)="onCreateGame()"><mat-icon >add</mat-icon>Create Guest</button>
<mat-form-field class="search-form-field" floatLabel="never">
<input matInput [(ngModel)]="searchKey" placeholder="Search" autocomplete="off" (keyup)="applyFilter()" >
<button mat-button matSuffix mat-icon-button aria-label="Clear" *ngIf="searchKey" (click)= "onSearchClear()">
<mat-icon>close</mat-icon>
</button>
</mat-form-field>
</div>
<div class="mat-elevation-z8">
<mat-table [dataSource]="listData">
<ng-container matColumnDef="gameName">
<mat-header-cell *matHeaderCellDef>Game Name</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.gameName}}</mat-cell>
</ng-container>
<ng-container matColumnDef="gameDate">
<mat-header-cell *matHeaderCellDef>Game Date</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.gameDate | date}}</mat-cell>
</ng-container>
<ng-container matColumnDef="gameVenue">
<mat-header-cell *matHeaderCellDef>Game Venue</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.gameVenue}}</mat-cell>
</ng-container>
<ng-container matColumnDef="homeTeam">
<mat-header-cell *matHeaderCellDef>Home Team</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.homeTeam}}</mat-cell>
</ng-container>
<ng-container matColumnDef="awayTeam">
<mat-header-cell *matHeaderCellDef>Away Team</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.awayTeam}}</mat-cell>
</ng-container>
<ng-container matColumnDef="numberOfGuest">
<mat-header-cell *matHeaderCellDef>No of Guest</mat-header-cell>
<mat-cell *matCellDef="let element">{{element.numberOfGuest}}</mat-cell>
</ng-container>
<ng-container matColumnDef="loading">
<mat-footer-cell *matFooterCellDef colspan="6">
Loding data...
</mat-footer-cell>
</ng-container>
<ng-container matColumnDef="noData">
<mat-footer-cell *matFooterCellDef colspan="6">
No data.
</mat-footer-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns:displayedColumns;"></mat-row>
<mat-footer-row *matFooterRowDef="['loading']" [ngClass]="{'hide': listData!=null}"></mat-footer-row>
<mat-footer-row *matFooterRowDef="['noData']" [ngClass]="{'hide': !(listData!=null && listData.data.length==0)}"></mat-footer-row>
</mat-table>
<mat-paginator [pageSizeOptions]="[5,10,25,100]" pageSize="5" showFirstLastButtons></mat-paginator>
</div>
home.component.ts
import { LoginService } from './../service/login.service';
import { AddgameComponent } from './../addgame/addgame.component';
import { GameService } from './../service/game.service';
import { MatTableDataSource, MatTable } from '@angular/material/table';
import { Component, OnInit, ViewChild, ChangeDetectorRef, AfterContentChecked, OnDestroy } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit{
constructor(public loginService : LoginService,public gameService :GameService, public dialog : MatDialog) { }
listData : MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator : MatPaginator
displayedColumns : string[] = ['gameName','gameDate','gameVenue', 'homeTeam','awayTeam','numberOfGuest'];
ngOnInit(): void
{
this.starter();
}
starter()
{
this.gameService.getAllGamesFromRemote().subscribe(
data =>{
let array = data;
this.listData = new MatTableDataSource(array);
this.listData.paginator = this.paginator;
this.listData.filterPredicate = (data, filter) => (data.gameName.trim().toLowerCase().indexOf(filter.trim().toLowerCase()) !== -1 ||data.homeTeam.trim().toLowerCase().indexOf(filter.trim().toLowerCase()) !== -1 );
});
}
searchKey : string = "";
onSearchClear()
{
this.searchKey = "";
this.applyFilter();
}
applyFilter()
{
this.listData.filter = this.searchKey.trim().toLowerCase();
}
onCreateGame()
{
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus=true;
dialogConfig.width="60%";
this.dialog.open(AddgameComponent, dialogConfig);
}
}
addgame.component.html
<mat-toolbar>
<span>Add new Game</span>
<span class="filler"></span>
<button class="btn-dialog-close" mat-stroked-button (click)="onClose()" tabindex="-1"><mat-icon>close</mat-icon></button>
</mat-toolbar>
<form class="normal-form" [formGroup]="gameService.gameForm" autocomplete="off" (submit)="onSubmit()">
<div class="controls-container">
<mat-form-field>
<input matInput formControlName="gameName" placeholder="Game Name*">
<mat-error *ngIf="gameService.gameForm.controls['gameName'].errors?.required">This is Mandatory Field</mat-error>
<mat-error *ngIf="gameService.gameForm.controls['gameName'].errors?.notUnique">Game name should be Unique</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="gameVenue" placeholder="Game Venue*">
<mat-error>This is Mandatory Field</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="homeTeam" placeholder="Home Team*">
<mat-error>This is Mandatory Field</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="awayTeam" placeholder="Away Team*">
<mat-error>This is Mandatory Field</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput formControlName="gameDate" [matDatepicker]="picker" placeholder="Game Date*">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
<mat-error>This is Mandatory Field</mat-error>
</mat-form-field>
<input type="hidden" formControlName="gameName" placeholder="Game Name*">
<div style="text-align: center;">
<button mat-raised-button color="primary" type="submit" [disabled]="gameService.gameForm.invalid">Add Game</button>
</div>
</div>
</form>
addgame.component.ts
import { Router } from '@angular/router';
import { NotificationService } from './../service/notification.service';
import { GameService } from './../service/game.service';
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { MatDialogRef } from '@angular/material/dialog';
@Component({
selector: 'app-addgame',
templateUrl: './addgame.component.html',
styleUrls: ['./addgame.component.css']
})
export class AddgameComponent implements OnInit {
constructor(public gameService : GameService, public notificationService : NotificationService, private datePipe: DatePipe, public dialogRef : MatDialogRef<AddgameComponent>, public router : Router) { }
ngOnInit(): void {
}
onSubmit()
{
this.gameService.addGameToRemote(this.gameService.gameForm.value).subscribe(
data=>{
this.notificationService.success("Game Added Sucessfully");
this.gameService.initializeForm();
console.log("Game added");
this.gameService.gameForm.reset();
this.onClose();
},
error=>{
this.gameService.gameForm.controls['gameName'].setErrors({"notUnique": true});
this.notificationService.error("Game name already taken");
console.log("Error in adding Game")
}
)
}
onClose()
{
this.gameService.gameForm.reset();
this.gameService.initializeForm();
this.dialogRef.close();
}
}
解决方案
您可以尝试在对话框关闭后重新调用 REST API 以再次获取所有游戏。为此,您可以使用以下代码:
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = true;
dialogConfig.autoFocus=true;
dialogConfig.width="60%";
dialogConfig.data = {somedata: 'data'};
const dialogId = this.dialog.open(AddgameComponent, dialogConfig);
const dialogSubmitSubscription = dialogId .componentInstance.onDialogueClose.subscribe(result => {
if(result) {
this.starter();
}
dialogSubmitSubscription.unsubscribe();
});
此外,如果您的表在数据动态更改后没有更新,那么您可能需要调用 Angular 的 ngOnChanges Hook。
ngOnChanges(changes: SimpleChange) {
if (changes["tableData"]) {
this.data = new MatTableDataSource(this.tableData);
if (this.data != undefined) {
this.data = new MatTableDataSource(this.tableData);
this.data.sort = this.sort;
}
setTimeout(() => {
this.data.paginator = this.paginator;
this.data.sort = this.sort;
});
}
}
希望这个答案有助于解决您的问题。
推荐阅读
- ios - 捏手势后如何将UIView动画化回原始帧
- python - 在熊猫数据框上应用以字符串格式存储的过滤器
- c++ - 命令“new”和“malloc”没有正确分配内存
- jenkins - 当电子邮件 ID 正确时,发送到以下有效地址 Jenkins 时出错?
- php - laravel 为现有数据库设置模型
- html - 创建简单的 html 电子邮件需要哪些 html 标签?
- sql - 如何使用单个查询从一个表中获得基于两个不同条件的多个结果
- django - DRF - 通过 url 更改文件字段
- python - 在任务中运行组时芹菜运行线程卡住
- java - 添加到工作项目后,谷歌地图未显示