Angular - HTML 在指令中找不到元素
Angular - HTML element not found in directive
我正在尝试使用 Angular 中的指令在元素上创建饼图 5. 我创建了如下指令:
@Directive({
selector: '[pieChart]'
})
export class PieChartDirective implements AfterViewInit {
@Input() pieChart: any;
@Input() pieChartElementId: string;
@Input() pieChartData: any;
constructor(elem: ElementRef, renderer: Renderer2) {}
ngAfterViewInit() {
this.generatePieChart(this.pieChartElementId);
}
generatePieChart(elemId) {
var values = [1, 2, 3];
$('#' + elemId).sparkline(values, {
type: "pie",
tooltipFormat: '{{offset:offset}} ({{percent.1}}%)',
tooltipValueLookups: {
'offset': {
0: 'First',
1: 'Second',
2: 'Third'
}
},
});
}
}
在模板中,我调用指令如下:
<div class="pieChartDiv" [attr.id]="'classroom.field1' + '_'+ i" [pieChart]="'classroom.field1' + '_'+ i" [pieChartElementId]="'classroom.field1' + '_'+ i"></div>
我正在动态创建 id
并想在每个 ID 上绘制饼图。但不幸的是,在指令文件中使用 console.log($("#"+this.pieChartElementId).length)
时,我没有得到指令中元素的长度。由于图表无法正常工作,因为它们没有获取元素。谁能告诉我为什么会这样。
提前致谢。
您不应使用 JQuery #() select 或与 Angular 一起使用:如您所见,即使在视图初始化之后,您的 pieChartElementId 元素也可能尚未呈现。
您应该使用 elementRef
或 @ViewChild
:
如果 pieChartElementId
是应用了 pieChart
指令的元素,您应该使用:
elementRef.nativeElement
如果你想select另一个元素,那就有点复杂了。您必须使用 @ViewChild
来获取元素:
@ViewChild('pieChartElement')
pieChartElement;
然后传递给指令输入:
<div pieChart [externalElement]="pieChartElement">
Element with directive
</div>
<p #pieChartElement>
External element
</p>
看到这个working example
我正在尝试使用 Angular 中的指令在元素上创建饼图 5. 我创建了如下指令:
@Directive({
selector: '[pieChart]'
})
export class PieChartDirective implements AfterViewInit {
@Input() pieChart: any;
@Input() pieChartElementId: string;
@Input() pieChartData: any;
constructor(elem: ElementRef, renderer: Renderer2) {}
ngAfterViewInit() {
this.generatePieChart(this.pieChartElementId);
}
generatePieChart(elemId) {
var values = [1, 2, 3];
$('#' + elemId).sparkline(values, {
type: "pie",
tooltipFormat: '{{offset:offset}} ({{percent.1}}%)',
tooltipValueLookups: {
'offset': {
0: 'First',
1: 'Second',
2: 'Third'
}
},
});
}
}
在模板中,我调用指令如下:
<div class="pieChartDiv" [attr.id]="'classroom.field1' + '_'+ i" [pieChart]="'classroom.field1' + '_'+ i" [pieChartElementId]="'classroom.field1' + '_'+ i"></div>
我正在动态创建 id
并想在每个 ID 上绘制饼图。但不幸的是,在指令文件中使用 console.log($("#"+this.pieChartElementId).length)
时,我没有得到指令中元素的长度。由于图表无法正常工作,因为它们没有获取元素。谁能告诉我为什么会这样。
提前致谢。
您不应使用 JQuery #() select 或与 Angular 一起使用:如您所见,即使在视图初始化之后,您的 pieChartElementId 元素也可能尚未呈现。
您应该使用 elementRef
或 @ViewChild
:
如果
pieChartElementId
是应用了pieChart
指令的元素,您应该使用:elementRef.nativeElement
如果你想select另一个元素,那就有点复杂了。您必须使用
@ViewChild
来获取元素:@ViewChild('pieChartElement') pieChartElement;
然后传递给指令输入:
<div pieChart [externalElement]="pieChartElement"> Element with directive </div> <p #pieChartElement> External element </p>
看到这个working example