Home > Software engineering >  How to Get the ID from html dom in angular14
How to Get the ID from html dom in angular14

Time:09-09

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  (click)="toHome()" href="#homebanner">Home</a></li>
<li> <a  (click)="toservice()"  href="#service">Service</a></li>
<li> <a  (click)="tohowitwork()" href="#howitwork">How it Works</a></li> 

CodePudding user response:

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  (click)="toHome()" href="#homebanner">Home</a>
</li>
<li>
  <a #service  (click)="toservice()" href="#service">Service</a>
</li>
<li>
  <a #howItWorks  (click)="tohowitwork()" href="#howitwork"
    >How it Works</a
  >
</li>

Current {{ name }}

forked stackblitz

  • Related