我需要向表中添加新行,即创建一个新元素,并将其插入到具有新数据的相应行之后。 https://stackblitz.com/edit/angular-fufyk5?file=src%2Fapp%2Fapp.component.ts 您可以看到我已经完成的工作,但是我不太擅长使用angular 2中的DOM。 表应该像这里的树一样https://material.angular.io/components/tree/overview
component.html
<table class="mat-table mat-elevation-z8">
<thead>
<tr class="mat-header-row">
<th class="mat-header-cell">Наименование</th>
<th class="mat-header-cell">Тип</th>
<th class="mat-header-cell">Действия</th>
</tr>
</thead>
<tbody>
<tr class="mat-row"
*ngFor="let item of items">
<td class="mat-cell">
<span *ngIf="item.has_child"
(click)="onClick($event)">>
</span>
<span>{{item.title}}</span>
</td>
<td class="mat-cell"> {{item.type.system_name}}</td>
<td class="mat-cell"> {{item}}</td>
</tr>
</tbody>
</table>
component.ts
import {Component, ElementRef, OnInit, Renderer2} from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
items: any = [
{
'id': '48ff51f8-a361-4430-a508-bf1f866db785',
'type': {
'system_name': 'default'
},
'enabled': true,
'can_remove': true,
'has_child': false,
'has_problem_link': null,
'has_problem_locale': null,
'title': 'Расстояние'
},
{
'id': '48a941b2-6fc9-4f8b-bfbc-8dcbfc6ce971',
'type': {
'system_name': 'default'
},
'enabled': true,
'can_remove': true,
'has_child': true,
'has_problem_link': null,
'has_problem_locale': null,
'title': 'Температура'
}
];
constructor(private elRef: ElementRef,
private renderer: Renderer2) {
}
onClick(event) {
const tr = this.renderer.createElement('tr');
console.log(event.path[2]);
this.renderer.appendChild(tr, this.renderer.createText('Namaste!!!!!'));
this.renderer.appendChild(event.path[2], tr);
}
}
答案 0 :(得分:0)
示例解决方案可能是:
ts:
items = [
{
has_child: true,
title: 'testTitle',
type: {
system_name: 'testSystemName'
},
expanded: false,
details: 'test details test details test details test details test details'
}
];
showDetails(item) {
item.expanded = true;
}
html:
<table class="mat-table mat-elevation-z8">
<thead>
<tr class="mat-header-row">
<th class="mat-header-cell">Наименование</th>
<th class="mat-header-cell">Тип</th>
<th class="mat-header-cell">Действия</th>
</tr>
</thead>
<tbody>
<ng-container *ngFor="let item of items">
<tr class="mat-row">
<td class="mat-cell">
<span *ngIf="item.has_child" (click)="showDetails(item)">></span>
<span>{{item.title}}</span>
</td>
<td class="mat-cell"> {{item.type.system_name}}</td>
<td class="mat-cell"> {{item}}</td>
</tr>
<tr *ngIf="item.expanded">
<td colspan="3">
{{item.details}}
</td>
</tr>
</ng-container>
</tbody>
</table>
我在expanded
的项目对象中添加了其他参数,最初将其设置为false,这意味着下面的行将被隐藏。
通过单击该>箭头,您将执行showDetails
,只需将详细信息扩展到行即可。