单击行不动态呈现子级时,Angular 2+ Datatables添加组件选择器

时间:2018-07-19 05:01:15

标签: angular datatables angular-datatables

我正在使用Angular DataTables来使用JQuery DataTables,但我一直试图找出如何实现this example from DataTables website的方法。我想改为动态显示一个组件,并在每次触摸一行时使组件扩展。我在click方法上使用了回调,以在触摸菜单时添加选择器,并在再次单击它时将其删除。表格上显示的菜单项来自JSON数据。当您单击该行时,它会从API创建一个值为selectorName的html组件选择器。

问题在于组件选择器确实出现并消失,但是子组件从未得到渲染。我添加了一个JQuery代码,通过在表行中添加CSS类来测试何时单击该行以更改行的颜色,并且它可以工作。

JSON菜单项

{
    "data": [
        {
            "selectorName": "employee-details",
            "name": "STUDENT DETAILS"
        },
        {
            "selectorName": "employee-training",
            "name": "EMPLOYEE TRAINING"
        },
    ]
}

menu.component.html

<table 
datatable 
[dtOptions]="dtOptions" 
[dtTrigger]="dtTrigger" 
class="row-border hover display" 
style="width: 100%"
id="table">
</table>

menu.component.ts

import { AfterViewInit, Component, OnInit, ViewChild } from '@angular/core';
import { DataTableDirective } from 'angular-datatables';
import { Subject } from 'rxjs';
import * as $ from 'jquery';
@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.css']
})
export class MenuComponent implements OnInit, AfterViewInit {

    @ViewChild(DataTableDirective)
    dtElement: DataTableDirective;
    dtOptions: DataTables.Settings = {};
    dtTrigger: Subject<any> = new Subject();


    constructor() { }

    ngOnInit() {
        this.dtOptions = {
            paging: false,
            ordering: false,
            info: false,
            searching: false,
            ajax: '/api/menu.json',
            columns: [
                {
                    title: '',
                    data: 'name'
                }
            ],
            rowCallback: (row: Node, data: any[] | Object, index: number) => {
                var node = document.createElement("div");
                $('td', row).unbind('click');
                $('td', row).bind('click', () => {
                    var component = 'app-' + data['componentName'];
                    if ($(row).hasClass('selected')) {
                        $(row).removeClass('selected');
                        $(component).remove();
                    } else {
                        $(row).addClass('selected');
                        row.appendChild(
                           document.createElement(component)
                        );
                    }
                });
                return row;
            }
        }

    }
    ngAfterViewInit(): void {
        this.dtTrigger.next();
    }
}

员工详细信息

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-employee-details',
  templateUrl: './employee-details.component.html',
  styleUrls: ['./employee-details.component.css']
})
export class EmployeeDetailsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    console.log('HERE"S JOHNNY')
  }

}

0 个答案:

没有答案