Home > other >  How to find the length of class name in angular 12
How to find the length of class name in angular 12

Time:12-06

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" ></div>
   </mag-dropdown>

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

  <mag-dropdown>
   <div id="general-dp" ></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/app/app.component.html,src/app/app.component.ts

CodePudding user response:

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);
  }
  • Related