EMahan K
EMahan K

Reputation: 467

How to find the length of class name in angular 12

Trying to get the length of dropdown class name which one have 'vehicle-disabled' class name.

I have tried but not working i do not know how to calculate particular length of class name( .vehicle-disabled ). If anyone knows please help to find the solution.

app.component.html:

<div #gdropdown>
   <mag-dropdown>
     <div id="general-dp" class="vehicle-disabled"></div>
   </mag-dropdown>

  <mag-dropdown>
    <div id="general-dp" class=""></div>
  </mag-dropdown>

  <mag-dropdown>
   <div id="general-dp" class="vehicle-disabled"></div>
  </mag-dropdown>
</div>

app.component.ts:

    export class AppComponent implements OnInit {
      name = 'Angular ' + VERSION.major;
      @ViewChild('gdropdown') finddisabled: ElementRef<HTMLElement>;
 
    ngOnInit(){

    let arr= []; 
    const dom: HTMLElement = this.finddisabled.nativeElement;
    const elements = dom.querySelectorAll('.vehicle-disabled'); 
    this.arr.push(elements); 
    console.log(arr.length);

   } 
   }

Demo: https://stackblitz.com/edit/angular-ivy-5kc12t?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

Upvotes: 0

Views: 266

Answers (1)

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

This answer is based on the expectation, that you mean amount of elements with this classname. (The length of 'vehicle-disabled' is obviously 16, since this classname has 16 characters)

Please use AfterViewInit instead of OnInit and use the actual array length

  ngAfterViewInit() {
    const dom: HTMLElement = this.finddisabled.nativeElement;
    const elements = dom.querySelectorAll('.vehicle-disabled');
    console.log(elements.length);
  }

Upvotes: 1

Related Questions