angularangular8angular-input

Give dynamic ID to a div which comes from other parent component


I have a chart component like below:

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

I am manipulating all the styles of this chart by it's parent div here which has id="chart", but I need above same component 2 times in a parent component! So that creates problem with same 2 ids.

So, I decided to pass div's id from parent component as an @Input() like below:

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

Edit on child component:

TS File:

@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}}"

but none of above worked to set the dynamic id from Input.


Solution

  • HTML:

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

    component:

    @Input() chartId: string;
    ngOnChanges(): void {
        const parent_div = document.getElementById('chart');
        parent_div.setAttribute('id', this.chartId);
    }
    

    In your child component give some initial id as a default value and use ngOnChanges to update the id.