我使用jQuery dataTable在列表视图上显示数据。我尝试使用以下方式将数据绑定到dataTable。
在users.component.ts
getUsers() {
this.UserService.getUsersList()
.subscribe(
success => {
this.userList = success;
$("#userTable").find('tbody').empty();
var dataClaims = this.userList;
for (let i = 0; i < dataClaims.length; i++) {
$('#userTable').dataTable().fnAddData([
(i + 1),
dataClaims[i].name,
dataClaims[i].email,
dataClaims[i].contact_number,
dataClaims[i].address,
'<a [routerLink]="[' +"'"+"../../user/update" +"'" +']"' + ' class="fa fa-1x fa-pencil-square-o"></a>',
]);
}
}
);
}
以上功能正常工作,dataTable正常运行。
但 [routerLink]
未转换为HTML 。在输出上,它按以下方式显示,
<a [routerlink]="['../../user/update']" class="fa fa-1x fa-pencil-square-o"></a>
但它应该转换为以下方式,
<a _ngcontent-c0="" ng-reflect-router-link="user/update" href="/user/update" class="fa fa-1x fa-pencil-square-o"></a>
有人可以解释在从.ts文件渲染html数据时如何将[routerlink]
转换为普通链接。谢谢。
答案 0 :(得分:2)
如果你真的想使用dataTable,也许这对你有帮助:
https://stackoverflow.com/a/38983367/2624360
基本上你应该创建一个封装dataTable逻辑的指令。
import {Directive, ElementRef} from '@angular/core';
import {Input, OnInit} from '@angular/core';
import { JqueryDataTableEvent } from './jquery-datable-event';
import 'jquery.dataTables';
declare var jQuery:any;
@Directive({
selector: '[jqueryDatatable]'
})
export class JqueryDatatableDirective implements OnInit {
private _datatable : any;
@Input()
jqueryDatatable: any;
@Input()
dataTableEvents: JqueryDataTableEvent[];
constructor(private _element: ElementRef) {}
ngOnInit() {
this.applyOptions();
this.applyEvents();
}
applyOptions()
{
if (!this.jqueryDatatable)
console.error("Empty options array was passed to initialize jqueryDatatable.");
this._datatable = jQuery(this._element.nativeElement).DataTable( this.jqueryDatatable || {} );
}
applyEvents() {
this.dataTableEvents.map((event)=> {
this._datatable.on(event.eventName, event.selector, event.callback)
});
}
}
有人(@ DarioN1)用这个创建和示例:
答案 1 :(得分:0)
你必须告诉Angular your HTML is safe:
import { DomSanitizer } from '@angular/platform-browser';
export class UserComponent {
constructor(private sanitizer: DomSanitizer) {}
getUsers() {
this.UserService.getUsersList()
.subscribe(
success => {
this.userList = success;
$("#userTable").find('tbody').empty();
var dataClaims = this.userList;
for (let i = 0; i < dataClaims.length; i++) {
$('#userTable').dataTable().fnAddData([
(i + 1),
dataClaims[i].name,
dataClaims[i].email,
dataClaims[i].contact_number,
dataClaims[i].address,
this.sanitizer.bypassSecurityTrustHtml('<a [routerLink]="[' +"'"+"../../user/update" +"'" +']"' + ' class="fa fa-1x fa-pencil-square-o"></a>'),
]);
}
}
);
}
}
&#13;
答案 2 :(得分:0)
[routerLink]不起作用。您需要使用 innerHTML 功能。
ts文件: -
tool = '<a href="../../user/update" class="fa fa-1x fa-pencil-square-o">View</a>';
html文件: -
<div [innerHTML]="tool"></div>
输出: -
<div _ngcontent-c1=""><a href="../../user/update" class="fa fa-1x fa-pencil-square-o">View</a></div>