为来自其他父组件的div提供动态ID

时间:2020-02-28 08:59:36

标签: angular angular8 angular-input

我有一个图表组件,如下所示:

<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>

我在这里通过具有id="chart"的父div来操纵该图表的所有样式,但是在父组件中我需要两次以上相同的组件!这样就产生了两个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>

我尝试了以下技术:[id] =“ chartId”,[attr.id] =“ chartId”,id =“ {{chartId}}”

,但是以上方法均无法通过Input设置动态ID。

3 个答案:

答案 0 :(得分:3)

HTML:

apiCall()

组件:

<div id="chart"> </div>

在您的子组件中,提供一些初始ID作为默认值,并使用ngOnChanges来更新ID。

答案 1 :(得分:1)

在父component.html中:

<div class="container">
    <!-- Other tags -->
    <child-component chartId="users"></child-component>
    <!-- Other tags -->
    <child-component chartId="visuals"></child-component>
    <!-- Other tags -->
</div>

和您的子component.ts中:

@Input() chartId: string;

并在您的子component.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>

编辑

如果上述解决方案对您不起作用,请尝试以下操作:

在父component.ts文件中的

声明两个变量:

users: string = 'yourID1';
visuals: string = 'yourID2';

并在parent component.html中:

<div class="container">
    <!-- Other tags -->
    <child-component [chartId]="users"></child-component>
    <!-- Other tags -->
    <child-component [chartId]="visuals"></child-component>
    <!-- Other tags -->
</div>

我希望这会有所帮助

答案 2 :(得分:0)

有时问题出在您的ViewEncapsulation级别。 甚至,如果您尝试在<ngx-charts-bar-horizontal/>内设置dom元素的样式。

我认为您可以在 ChildComponent 中使用 ViewEncapsulation.None 选项。