我有一个如下所示的图表组件:
<div id="chart">
<ngx-charts-bar-horizontal [view]="view" [trimYAxisTicks]="false" [xAxisTickFormatting]="convertDecimalToNumber" [scheme]="colorScheme" [results]="data" [gradient]="gradient" [xAxis]="showXAxis" [yAxis]="showYAxis" [showXAxisLabel]="showXAxisLabel" [showDataLabel]="showDataLabel" [xAxisLabel]="xAxisLabel" [barPadding]="40">
</ngx-charts-bar-horizontal>
</div>
我正在通过它的父 div 处理这个图表的所有样式,它有 id="chart"
,但我需要在父组件中使用上面相同的组件 2 次!所以这会产生相同 2 个 ID 的问题。
所以,我决定从父组件将 div 的 id 作为 @Input()
传递,如下所示:
<div class="container">
<!-- Other tags -->
<child-component [chartId]="users"></child-component>
<!-- Other tags -->
<child-component [chartId]="visuals"></child-component>
<!-- Other tags -->
</div>
在子组件上编辑:
TS 文件:
@Input() chartId: string;
HTML:
<div [id]="chartId">
<ngx-charts-bar-horizontal [view]="view" [trimYAxisTicks]="false" [xAxisTickFormatting]="convertDecimalToNumber" [scheme]="colorScheme" [results]="data" [gradient]="gradient" [xAxis]="showXAxis" [yAxis]="showYAxis" [showXAxisLabel]="showXAxisLabel" [showDataLabel]="showDataLabel" [xAxisLabel]="xAxisLabel" [barPadding]="40">
</ngx-charts-bar-horizontal>
</div>
I tried these techniques: [id]="chartId", [attr.id]="chartId", id="{{chartId}}"
但以上都无法从输入中设置动态 ID。
最佳答案
HTML:
<div id="chart"> </div>
组件:
@Input() chartId: string;
ngOnChanges(): void {
const parent_div = document.getElementById('chart');
parent_div.setAttribute('id', this.chartId);
}
在您的子组件中提供一些初始 id 作为默认值并使用 ngOnChanges 更新 id。
关于angular - 为来自其他父组件的 div 提供动态 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60448293/