[英]How to use a variable in a template in angular 2
I have a component which has chartid as a input which I use like this: 我有一个将chartid作为输入的组件,我这样使用:
<plotlychart chartid="plot">
</plotlychart>
This is the component. 这就是组件。 In the template I try to set the id of the div to the variable "chartid", but this is not working.
在模板中,我尝试将div的ID设置为变量“ chartid”,但这不起作用。
@Component({
selector: 'plotlychart',
template: `
<div [id]="chartid"
style="width: 480px; height: 400px;">
<!-- Plotly chart will be drawn inside this DIV -->
</div>
`,
styleUrls: []
})
export class PlotlyComponent{
@Input() chartid: string;
}
My question is: Is it possible to use the value of chartid in the template of the component? 我的问题是:是否可以在组件模板中使用chartid的值?
Solution 解
<plotlychart chartid="plot">
</plotlychart>
In component: 在组件中:
@Component({
selector: 'plotlychart',
template: `
<div id="{{chartid}}"
style="width: 480px; height: 400px;">
<!-- Plotly chart will be drawn inside this DIV -->
</div>
`,
styleUrls: []
})
export class PlotlyComponent{
@Input() chartid: string;
ngAfterViewInit(){
Plotly.newPlot(this.chartid, this.data, this.layout, this.options);
}
}
Your <plotlychart>
should be like this: 您的
<plotlychart>
应该是这样的:
<plotlychart [chartid]="plot"> </plotlychart> <!-- (note the [] here!) -->
Now in your PlotlyComponent template you could just use interpolation for the chartid
, like so: 现在,在您的PlotlyComponent模板中,您可以对
chartid
使用插值,如下所示:
template: `
<div id="{{ chartid }}"
style="width: 480px; height: 400px;">
<!-- Plotly chart will be drawn inside this DIV -->
</div>
`,
Further readings for you: 您的进一步阅读:
as the OP mentioned he is using Plotly... 正如OP 所说的,他正在使用Plotly ...
Try to wrap the Plotly.plot(this.chartid, ...)
in a AfterViewInit method. 尝试将
Plotly.plot(this.chartid, ...)
包装在AfterViewInit方法中。 I once had an issue where the component wasn't properly loaded and in the actual page DOM when I called Plotly. 曾经有个问题,当我调用Plotly时,组件没有正确加载,并且在实际的页面DOM中。 Using AfterViewInit ensures the DOM is setup before you call to the charting library.
使用AfterViewInit可以确保在调用图表库之前已设置DOM。
In your component: 在您的组件中:
ngAfterViewInit() {
Plotly.plot(this.chartid, yourdata, ...)
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.