0

I m using angular 14, Am tried to get an ID from HTML dom (Html component) in array form . Manually, I get Id from the HTML component in the TS file but dynamic or in the array is not conveying.

header.ts

  toHome() {
    const element = <HTMLElement>document.getElementById("home");
    return element;
  }
  
  toservice() {
    const element = <HTMLElement>document.getElementById("service");
    return element;
  }
  tohowitwork() {
    const element = <HTMLElement>document.getElementById("howitwork");
    return element;
  }
  toabout() {
    const element = <HTMLElement>document.getElementById("about");
    return element;
  }




 Header.component.html

<li><a class="nav-link" (click)="toHome()" href="#homebanner">Home</a></li>
<li> <a class="nav-link" (click)="toservice()"  href="#service">Service</a></li>
<li> <a class="nav-link" (click)="tohowitwork()" href="#howitwork">How it Works</a></li> 

1 Answers1

1

You need to use viewchild demo below.

ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  @ViewChild('home') home: ElementRef<any>;
  @ViewChild('service') service: ElementRef<any>;
  @ViewChild('howItWorks') howItWorks: ElementRef<any>;
  name = '';

  toHome() {
    return this.home;
  }

  toservice() {
    return this.service;
  }
  tohowitwork() {
    return this.howItWorks;
  }
}

html

<li>
  <a #home class="nav-link" (click)="toHome()" href="#homebanner">Home</a>
</li>
<li>
  <a #service class="nav-link" (click)="toservice()" href="#service">Service</a>
</li>
<li>
  <a #howItWorks class="nav-link" (click)="tohowitwork()" href="#howitwork"
    >How it Works</a
  >
</li>

Current {{ name }}

forked stackblitz

Naren Murali
  • 19,250
  • 3
  • 27
  • 54
  • 1
    @Shweta you need to use @ViewChildren and specify the same template name for all the elements you want E.g @ViewChildren('item') items: QuerySelector; then in html add the template ref as #item for all the `a` tags – Naren Murali Sep 08 '22 at 11:53