javascript - 将点击监听器添加到自定义按钮在 Angular 数据表中不起作用

标签 javascript angular datatables

我有一个数据表,如下所示:

<div class="card-body table-responsive">
          <table
            class="table display table-striped table-hover table-bordered row-border hover responsive nowrap"
            datatable
            [dtOptions]="dtOptions"
            datatable=""
            #dataTable
            id="issueTable"
          >
            <thead class="headColor"></thead>
            <tbody style="text-align: center;"></tbody>
          </table>
        </div>  

JS:

import { Component, OnInit, Renderer, AfterViewInit, ViewChild, HostListener } from '@angular/core';
import { Router, RouterLink } from '@angular/router';
import { routerTransition } from '../../router.animations';

import { DataTableDirective } from 'angular-datatables';

import { IssueDataServiceService } from './issue-data-service.service';


import 'datatables.net';
import 'datatables.net-bs4';

window['jQuery'] = window['$'] = $;

@Component({
    selector: 'app-charts',
    templateUrl: './issues.component.html',
    styleUrls: ['./issues.component.scss'],
    animations: [routerTransition()]
})
export class IssuesComponent implements OnInit, AfterViewInit {

    // viewer = document.getElementById('view');

    /**
     * gets settings of data tables
     *
     * @type {DataTables.Settings}
     * @memberof IssuesComponent
     */
    constructor(public router: Router) { }

    @ViewChild(DataTableDirective)
    datatableElement: DataTableDirective;
    message = '';
    title = 'angulardatatables';

    @ViewChild('dataTable') table: { nativeElement: any; };
    dataTable: any;
    dtOptions: DataTables.Settings = {};
    // someClickhandler(info: any): void {
    //     this.message = info.number + '-' + info.assignedto + '-' + info.company;
    //     console.log(this.message);
    // }
    ngOnInit(): void {
        this.dtOptions = {
            pagingType: 'full_numbers',
            pageLength: 15,
            processing: true,
            responsive: true,
            autoWidth: false,
            dom: 'Bfrtip',
            'ajax': {
                url: 'http://localhost:8080/incident-updated',
                type: 'GET',
                dataSrc: 'result',
            },
            columns: [
                {
                    title: 'Incident',
                    data: 'number'
                },
                {
                    title: 'Product',
                    data: 'u_product'
                },
                {
                    title: 'Status',
                    data: 'state'
                },
                {
                    title: 'Created By',
                    data: 'sys_created_by'
                },
                {
                    title: 'Group',
                    data: 'assignment_group'
                },
                {
                    title: 'Category',
                    data: 'u_category'
                },
                {
                    title: 'Updated on',
                    data: 'sys_updated_on'
                },
                {
                    title: 'Action',
                    data: null,
                    // render: function(data, type, full) {
                    //     return '<a class="btn btn-primary btn-sm" style="color: #fff;" id="view" (click)="view($event)">View</a>';
                    // }
                    defaultContent: '<button class="btn btn-sm btn-primary viewer"> View </button>'
                }
            ]
        };
        let table = this.dataTable;
        table = $(this.table.nativeElement);

        const _curClassRef = this;
        $('#issueTable tbody td').unbind();
        $('#issueTable tbody td').on('click', function (event: any) {
            event.stopPropagation();
            // const tr = $(this).closest('tr');
            // const row = table.row(tr);
            if (this.className = 'viewer') {
                _curClassRef.redirect();
            }
        });

        // function view($event: any) {
        //     event.stopPropagation();
        //     this.router.navigate(['/event-viewer']);
        // }
        // $('#viewer').on('click', function() {
        //     event.stopPropagation();
        //     this.router.navigate(['/event-viewer']);
        // });
        // console.log('table is ==>', this.dataTable);
        // $('#view tbody').on('click', 'button', function () {
        //     const data = this.dataTable.row($(this).parents('tr').data);
        //     alert('Data is ==>' + data);
        // });
    }
    redirect() {
        alert('alsjfhksjdf');
    }

    // @HostListener('click')
    // viewer() {
    //     event.stopPropagation();
    //     this.router.navigate(['/event-viewer']);
    // }

    ngAfterViewInit(): void {
        // Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
        // Add 'implements AfterViewInit' to the class.
        // this.viewer.addEventListener('click', function() {
        //     event.stopPropagation();
        //     // this.router.navigate(['/event-viewer']);
        //     alert('shdfiskludhzj');
        // });
    }
    // viewer() {
    //     alert('sdjfhsklzdjh');
    // }
    // viewer(event: any) {
    //     event.stopPropagation();
    //     this.router.navigate(['/event-viewer']);
    // }
    // buttonInRowClick(event: any): void {
    //     event.stopPropagation();
    //     console.log('Button in the row clicked.');
    //     this.router.navigate(['/event-viewer']);
    // }
    // wholeRowClick(): void {
    //     console.log('Whole row clicked.');
    // }
}  

但是当我点击按钮时,警报没有出现,我该如何解决?

最佳答案

您正在使用 ngOnInit,因此当您在此处使用 JQuery 时,Angular 可能没有时间渲染表格:

$('#issueTable tbody td').unbind();
$('#issueTable tbody td').on('click', function (event: any) {
    event.stopPropagation();
    // const tr = $(this).closest('tr');
    // const row = table.row(tr);
    if (this.className = 'viewer') {
        _curClassRef.redirect();
    }
});

尝试将此代码包装在 setTimeout(()=> { }) 中,如下所示:

setTimeout(()=> { 
    $('#issueTable tbody td').unbind();
    $('#issueTable tbody td').on('click', function (event: any) {
        event.stopPropagation();
        // const tr = $(this).closest('tr');
        // const row = table.row(tr);
        if (this.className = 'viewer') {
            _curClassRef.redirect();
        }
    });
})

通过这样做,您将强制执行一次更改检测,这将导致您的表被渲染。只有此时 Jquery 才能够选择您的 HTML 元素

关于javascript - 将点击监听器添加到自定义按钮在 Angular 数据表中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60411157/

相关文章:

javascript - 如何在改变可见性的同时改变背景?

jquery - 分页在数据表中不起作用,一次显示所有记录?

html - Bootstrap 3 模态背景缺失

javascript - 如何在DataTables 中绑定(bind)Openweather map API 数据?

javascript - 我应该在 angular.js 中的哪里编写通用 Controller 函数?

javascript - VueJS : Building for production. ..杀死

javascript - Angular 4 - 如何为原型(prototype)设计和开发模拟模拟数据

angular - 在 Angular 中为 Google 登录调用 data-onsuccess

jquery - 滑动/滑动标签 ionic 2

javascript - 将相机 W.R.T 3d 对象放置在 Three.js 中