【发布时间】:2018-06-14 03:08:26
【问题描述】:
我的简单任务是将在输入框中键入的文本添加到 mat-table,但它没有按预期工作。数据源只刷新了一次,并没有显示从第二次开始的更新数据。
这是我的代码 app.component.html
<div class="main" fxLayout="column" fxGap="10">
<div class="input-area">
<mat-form-field>
<input matInput placeholder="Type something" [(ngModel)]="currentText">
</mat-form-field>
<button mat-raised-button color="primary" style="margin-left:10px;" (click)="onAdd($event)">Add</button>
</div>
<div class="result-area">
<mat-table #table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="name">
<mat-header-cell #th *matHeaderCellDef> Name </mat-header-cell>
<mat-cell #td *matCellDef="let element"> {{element.name}} </mat-cell>
</ng-container>
<mat-header-row #tr *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row #tr *matRowDef="let row; columns: displayedColumns;"></mat-row>
</mat-table>
</div>
这是我的“app.component.ts”,其中包含更新表数据源的“添加”事件。
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
currentText: string= "";
displayedColumns = ['name'];
data: Data[] = [];
dataSource: Data[];
constructor(){}
onAdd($event){
this.data.push({name: this.currentText});
this.dataSource = this.data;
}
}
interface Data{
name: string;
}
我做错了什么? 这里是上面code的stackblitz例子@
【问题讨论】: