【问题标题】:How to use json2html with jquery within Angular?如何在 Angular 中使用 json2html 和 jquery?
【发布时间】:2019-04-13 12:08:28
【问题描述】:

我的任务是将现有的 UI 集成到另一个现有的 Angular 应用程序中,并被挂断了...

我知道数据 + 转换在 Angular 上下文之外运行良好。

我没有看到 jquery json2html 的 npm 包,所以我尝试通过将它保存在组件目录旁边以临时方式导入该部分。

它产生ERROR TypeError: $(...).json2html is not a function...

...
import * as $ from 'jquery';
import json2html from 'json2html';
import * from './jquery.json2html.min.js';

...

$('#myTable > tbody').json2html(data,transform);

【问题讨论】:

  • 在 Angular 中使用 jQuery 通常被视为一种反模式
  • 老实说,这感觉就像可以使用标准 Angular 模式超级简单完成的事情,而不需要任何类型的库......
  • 你为什么不在 Angular 中使用 jspdf(也许还有 html2canvas)? Here 是带有示例的指南。我在 Angular 6 中使用过它,它的工作原理就像一个魅力
  • @user184994 这就是为什么我包含有关集成两个独立应用程序的上下文的原因。目标是完成这项工作,即使它很脏。
  • @RaySoy 不,我不想要 PDF。我想要一个 DOM 中的交互式 HTML 表格。

标签: javascript angular json2html


【解决方案1】:
    npm install node-json2html


    ...
    import json2html from 'json2html';
    import * as $ from 'node-json2html';

    ...

ngAfterViewInit(){
    $('table#myTable > tbody').json2html(data,transform);

}

或者,

... 
import json2html from 'json2html';
import * as $ from './jquery.json2html.min.js';

...

$('table#myTable > tbody').json2html(data,transform);

链接:-http://www.json2html.com/

【讨论】:

  • 这样会报错,你已经把jquery导入为*,再做declare const $:any;会和之前的声明冲突
  • 这不起作用。您正在压缩 jquery 导入,就像提到的 @user184994 一样。
【解决方案2】:

在您必须在 angular.json 中添加 jQuery 之前,然后在要使用 jQuery 的组件中这样做

....
declare let $: any;    // you can use "jQuery" keyword instead of "$"

@component({
  selector: '...',
  templateUrl: ['...'],
  styleUrls: ['...']
})
export class JqueryExampleComponent implements onInit {

  constructor(private eleRef: ElementRef) {}

  ngOnInit() {
    $(this.eleRef.nativeElement).find('#myTable > tbody').json2html(data,transform);
  }
}

当您使用$(this.eleRef.nativeElement) 时,将获得component dom 的树根,然后.find('selector') 获得您想要的element

【讨论】:

  • 这里的问题是 json2html 不知何故不在范围内,而不是我无法使用 jquery 执行选择。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 2016-05-25
  • 2018-10-04
  • 2017-08-15
相关资源
最近更新 更多