问题描述
我是 Angular 数据表的新手。 如果以前隐藏了数据表,我该如何重新渲染它?
我有两个组件,父组件和子组件都通过基于标志的按钮点击来隐藏和显示。
预期: 如果通过子组件添加新行,我需要重新渲染表格。(代码不是为添加新行而编写的,而是应用了发射器。)请帮忙
父 HTML
<div [hidden]="!showlist">
<table datatable [dtOptions]="dtOptions" [dtTrigger]="dtTrigger" class="table table-striped table-bordered">
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>completed</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let user of todo">
<td> {{t.id}} </td>
<td> {{t.title}} </td>
<td> {{t.completed}} </td>
</tr>
</tbody>
</table>
<br/>
<div class="btn-group btn-group-justified">
<a class="btn btn-default">
<button class="btn btn-default" (click)="showChild()">ShowChild</button>
</a>
</div>
</div>
<hr>
<div *ngIf="!showlist">
<app-child (back)="showParent()" (rowAdded)="todo()">
</app-child>
</div>
家长 ts
export class AppComponent implements OnInit {
constructor(private http: HttpClient) {}
dtTrigger: Subject<any> = new Subject();
dtOptions: DataTables.Settings = {};
todo: Array<any>;
showlist: boolean;
ngOnInit(): void {
this.todo();
}
ngOnDestroy(): void {
this.dtTrigger.unsubscribe();
}
apiUrl = "https://jsonplaceholder.typicode.com/todos";
todo() {
this.showlist = true;
this.dtTrigger = new Subject();
this.dtTrigger.subscribe();
this.http.get<any[]>(this.apiUrl).subscribe(data => {
this.todo= data;
this.dtTrigger.next();
this.ngOnDestroy();
});
}
showChild() {
this.showlist = false;
}
showParent() {
this.showlist = true;
}
}
子 HTML
<button class="btn btn-default" (click)="addRow()">Add row</button>
<button class="btn btn-default" (click)="showParent()">ShowParent</button>
儿童 ts
export class ChildComponent implements OnInit {
@Output() rowAdded: EventEmitter<any> = new EventEmitter<any>();
@Output() back: EventEmitter<any> = new EventEmitter<any>();
constructor() {}
ngOnInit() {}
addRow() {
//code to add new row
this.rowAdded.emit();
}
showParent() {
this.back.emit();
}
}
还可以查看: STACKBLITZ DEMO CODE
解决方法
问题似乎出在您的变量名称上。他们是一样的。
-
Do[ Import["dMdt_protein_nve" <> ToString@i <> ".dat","Table"],{i,{980,998}}]
-
todo: Array<any>;
请重命名两者之一。然后再试一次。
这是一个关于 stackblitz 的 working example
编辑
修复命名问题后。
todo()
为什么会这样?
根据angular-datatables source code。每次调用时发出带有 todo() {
this.showlist = true;
this.dtTrigger = new Subject();
this.dtTrigger.subscribe();
this.http.get<any[]>(this.apiUrl).subscribe(data => {
console.log(data);
this.todoList = data;
this.dtTrigger.next();
// remove unsubscribe after get all data.
});
}
主题的新值。这会调用一个名为 dtTrigger
dtTrigger 注释
手动触发DT渲染时使用此触发器
- 在渲染角度渲染的 DOM 时很有用
如果您在获取数据后取消订阅。桌子走开。
这是一个关于 stackblitz 的 working example
编辑 2
看起来渲染表有问题。它已重写所有表并触发 this issue
接下来我销毁了数据表的实例并重新创建了新的实例。