Transform getElementsByClassName into elementRef

Asked

Viewed 48 times

0

I made a code and would like to transform my getElementsByClassName and elementRef, below show how I did and how I tried to adjust

tabContent = this.tabContent.nativeElement.innerHTML;
    for (i = 0; i < tabContent.length; i++) {
      tabContent[i].style.display = 'none';
    }
    tablinks = document.getElementsByClassName('tablinks');
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(' active', '');
    }

1 answer

2


For you to pick up any element Html in the native syntax of JavaScript and transform to Angular you can use the decorator @Viewchild() and the typing of the variable as being of the type Elementref which enables you to access all properties of that element through the attribute nativeElement:

In your case there the variable tabContent is already a @Viewchild() so tablinks would follow the same logic:

// Faz os imports
import { Component, ElementRef, ViewChild } from '@angular/core';

// decalara a variável e o tipo como ElementRef
@ViewChild('tablinks', {static, false}) tablinks: ElementRef;

tabContent = this.tabContent.nativeElement.innerHTML;
for (i = 0; i < tabContent.length; i++) {
  tabContent[i].style.display = 'none';
}
for (i = 0; i < tablinks.length; i++) {
  tablinks[i].className = tablinks[i].className.replace(' active', '');
}

Depending on the version of Angular you are using (I think from 7 up) it is necessary to declare an object stating whether the variable instance is static or not: {static, true}

  • Why not? I don’t understand!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.