-1

Trying to add classname and set some style for td of each tr in the table using typescript. I have tried, But it is not working. If anyone knows please help to find the solution.

app.component.ts:

  ngOnInit() {
   this.elRef.nativeElement
  .querySelectorAll('#contect table tbody tr')
  .forEach((element, index, array) => {
    console.log(element);

    element.forEach((element, index, array) => {
      if (index == 0) {//first td of tr
        element.classList.add('bg');
        element.style.right = '2px';
      } 
    });
  });
  }
  }
EMahan K
  • 417
  • 1
  • 19

1 Answers1

0
  1. Typo: "content" not "contect"

  2. Add element.querySelectorAll('td')

  3. Specify HTMLElement as the generic type for ElementRef and querySelectorAll to get type support.

  constructor(public elRef: ElementRef<HTMLElement>) {}

  ngOnInit() {
    this.elRef.nativeElement
      .querySelectorAll<HTMLElement>('#content table tbody tr')
      .forEach((element) => {
        element.querySelectorAll('td').forEach((element, index) => {
          if (index < 2) element.classList.add('bg');
        });
      });
  }

Stackblitz: https://stackblitz.com/edit/angular-svg-use-lw5uhc?file=src/app/app.component.ts

Chris Hamilton
  • 9,252
  • 1
  • 9
  • 26
  • How to apply these css only for the first two column(company and contact? – EMahan K Feb 06 '23 at 15:27
  • If this solved your problem please accept this answer and ask a different question. You can post the link here. – Chris Hamilton Feb 06 '23 at 15:29
  • This is not resolved my issue. Please check my equation. Actually i am trying to apply css for the first two column. So, Please update your stackblitz – EMahan K Feb 06 '23 at 15:33
  • You have any idea? – EMahan K Feb 06 '23 at 15:52
  • @EMahanK `element.forEach(...)` doesn't work because `HTMLTableRowElement` doesn't have the `forEach()` method defined. You can however use `Array.from(element.cells).forEach(...)`. But like already stated in the comments of the question, you're probably better of defining the classes in the template instead. – 3limin4t0r Feb 06 '23 at 16:01
  • @3limin4t0r: Can you edit my stackblitz? – EMahan K Feb 06 '23 at 16:03
  • @EMahanK Fixed TypeScript: https://stackblitz.com/edit/75362846-3982562-01?file=src%2Fapp%2Fapp.component.ts Or the alternative with classes and styles defined in the template https://stackblitz.com/edit/75362846-3982562-02?file=src%2Fapp%2Fapp.component.ts&file=src%2Fapp%2Fapp.component.html – 3limin4t0r Feb 06 '23 at 17:10
  • @EMahanK edited to only change first two columns – Chris Hamilton Feb 07 '23 at 04:52