Home > Software design >  How to access looped div tag in Typescript file
How to access looped div tag in Typescript file

Time:02-14

<div    style="box-shadow: 0 -1px 0 0 rgb(0 0 0 / 10%);">
    <div #myDiv (click)="navToOrder(value.agId,value.invoiceId,value.tableNo,value.currStageName)" [style.background-color]="value.currStageColor"

          *ngFor="let value of dashBoardTableList ;let i=index"     
        tooltip={{value.currStageName}} placement="top">
        <span >{{value.noOfCovers}}</span>
        <span >
            <i *ngIf="value.currStageName!='Empty'" ></i>
            <i *ngIf="value.currStageName=='Empty'" ></i>
        </span>
        <span >
            <i  style="font-size:35px;"></i><i 
                style="font-size: 15px;top: 5px;left: -1.5px;"></i>
        </span>
        <span >
            <i *ngIf="value.currStageName!='Empty'" ></i>
            <i *ngIf="value.currStageName=='Empty'" ></i>
        </span>

        <span >{{value.tableNo}}</span>

    </div>
</div>

Here I want to get a specific index of div tag unfortunately Tabindex is not working fine.Is there any other way ?

CodePudding user response:

Applying styles using @ViewChild is generally an Angular anti-pattern.

It sounds like what you really want here is a Directive that takes the index of the element as an argument, something like:

import { AfterViewInit, Directive, ElementRef, Input, Renderer2 } from '@angular/core';

@Directive({
  selector: 'myStyleDirective'
})
export class MyStyleDirective implements AfterViewInit {
  @Input() itemIndex!: number;
  
  constructor(private el: ElementRef, private renderer: Renderer2) {}
  
  ngAfterViewInit() {
    const styleValue = this.itemIndex % 2 === 0 ? 'even' : 'odd';
    this.renderer.setStyle(this.el.nativeElement, 'styleToChange', styleValue);
  }
}

You then place the directive on your element:

<div *ngFor="let value of dashBoardTableList ;let i=index"
     myStyleDirective
     [itemIndex]="i"
     (click)="navToOrder(value.agId,value.invoiceId,value.tableNo,value.currStageName)"
     [style.background-color]="value.currStageColor"
     
     tooltip={{value.currStageName}}
     placement="top">

You could also use [ngStyle] or [ngClass] and use a method in your TypeScript which returns the appropriate style for a given index. There can be performance issues with that, though, as the method gets called for every change detection cycle.

CodePudding user response:

I've voted for the answer of @Will Alexander, but for code, there are minor issues I'll fix it here. for the selector name, fix it to be [myStyleDirective] instead of 'myStyleDirective'
And for setStyle method make sure that you are passing the correct parameters, especially for the name of the style and the value for the style
Here is a working example: Stackblitz

  • Related