【问题标题】:Object literal may only specify known properties, and 'select' does not exist in type 'Settings'对象字面量只能指定已知属性,而“设置”类型中不存在“选择”
【发布时间】:2020-02-26 23:55:43
【问题描述】:

当我尝试用 Angular 编写这段 javascript 代码时,我错过了什么?

 ngOnInit() {


  $('#jithesh').DataTable( {
    columnDefs: [ {
        orderable: false,
        className: 'select-checkbox',
        targets:   0
    } ],
    select: {
        style:    'os',
        selector: 'td:first-child'
    },
    order: [[ 1, 'asc' ]]
} );

这是原始的java脚本

$(document).ready(function() {
    $('#example').DataTable( {
        columnDefs: [ {
            orderable: false,
            className: 'select-checkbox',
            targets:   0
        } ],
        select: {
            style:    'os',
            selector: 'td:first-child'
        },
        order: [[ 1, 'asc' ]]
    } );
} );

试图遵循这个例子中的内容

https://datatables.net/extensions/select/examples/initialisation/checkbox.html

【问题讨论】:

    标签: javascript angular


    【解决方案1】:
    1. 如果可以的话,避免使用 Angular 的 jQuery

    2. 当您在 ngOnInit() 中运行 jQuery 时,您的元素不在 DOM 中。相反,请将您的代码从 ngOnInit() 移动到 ngAfterViewInit()

    演示:https://stackblitz.com/edit/angular-mn2776

    此演示向您展示了在组件的初始生命周期挂钩期间document.getElementById('id').outerHTML 的结果:

    • ngOnInit() - 未定义
    • ngAfterContentInit() - 未定义
    • ngAfterViewInit() - 外层HTML

    使用的代码:

      ngOnInit() {
        this.onInit = this.getOuterHtml();
      }
    
      ngAfterContentInit() {
        this.afterContentInit = this.getOuterHtml();
      }
    
      ngAfterViewInit() {
        setTimeout(() => {
          this.afterViewInit = this.getOuterHtml();
        })    
      }
    
      private getOuterHtml() {
        const el = document.getElementById('el');
        return el ? el.outerHTML : 'undefined';
      }
    

    文档:https://angular.io/guide/lifecycle-hooks

    【讨论】:

    • 或者更好的是,将 jquery 代码移动到包装该功能的指令中
    • @HarijsDeksnis 宝贝步骤!我认为在这种情况下,自定义指令对于答案来说太过分了。
    • 我在 angular 中很天真,仍然在 src/app/all-in-one/all-in-one.component.ts(53,7) 中收到此错误错误:错误 TS2345:参数类型'{ columnDefs:{可订购:假;类名:字符串;目标:数字; }[];选择:{风格:字符串;选择器:字符串; };顺序:(字符串|数字)[][]; }' 不可分配给“设置”类型的参数。对象字面量只能指定已知属性,而“设置”类型中不存在“选择”。
    • @JitheshChandra 听起来与您的原始问题无关。你能在我的 stackblitz 中重复我的实验吗,但是使用$('#jithesh')
    猜你喜欢
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-08-24
    • 2018-09-06
    • 2021-02-18
    • 2021-09-27
    • 2020-07-19
    相关资源
    最近更新 更多