[英]Angular - Array is not shown in mat-table
在 function 中,字符串被拆分为一个数组。 每个词都被发送到服务器,从那里我得到一些关于这个词的信息。 我保存到一个数组中。 我遇到的问题是,如果我 go 通过 HTML 文档中带有 *ngFor 的数组,我会得到所有条目,但在 mat-table 中,它没有显示。 我没有收到错误,只是没有显示数据。
sendText(){
this.words=[];
this.stringArray = this.sentence.split(" ");
console.log(this.stringArray);
for(let i=0;i<this.stringArray.length ;i++){
this.httpService.sendText(this.stringArray[i]).subscribe((res) => {
this.result = res;
console.log(this.result.words);
this.b.wort = this.result.words[0].wort;
this.b.definition = this.result.words[0].definition;
this.b.wortart = this.result.words[0].wortart;
this.words.push(this.b);
this.b = this.getemptyObject();
});} console.log(this.words); this.sentence = "";}
HTML
<div *ngFor="let word of words">
{{word.wort}},{{word.definition}}, {{word.wortart}}
</div>
<table mat-table [dataSource]="words" class="mat-elevation-z8">
<!-- Word Column -->
<ng-container matColumnDef="wort">
<th mat-header-cell *matHeaderCellDef> Wort </th>
<td mat-cell *matCellDef="let word"> {{word.wort}} </td>
</ng-container>
<!-- Wortdtype Column -->
<ng-container matColumnDef="wortart">
<th mat-header-cell *matHeaderCellDef> Wortart </th>
<td mat-cell *matCellDef="let word"> {{word.wortart}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
我在这个Reddit Thread上找到了这个问题的解决方案。
根据“@spacechimp”(回答问题的人)的说法,您需要更新整个数组以供 MatTable 检测更改。
像这样的东西:
this.words.push(this.b);
this.words = [...this.words]; // <--- Update the whole array with its own data
尽管这是一个解决方案,但对于大型 arrays 来说,这是一种相当昂贵的方法,因此我鼓励您找到其他方法来优化它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.