Get attribute id from component in directive

1.2k Views Asked by At

I am trying to get the attribute id of a component(header) in a custom directive. At the same time I am using a layout to show the header. For that I am using this.renderer.appendChild(this.elementRef.nativeElement, p); but the problem is that I need add this paragraph inside a specific div(<div #identifier class="mid"></div>). Here is my code:

HTML Layout

<div class="grid">
  <header mId id="navbar"></header>
</div>

Header Component

<div class="header-container">
  <h1 id="logo">...</h1>
  .
  .
  .
  <div #identifier class="mid"></div>
</div>

Directive

import { ContentChild, Directive, ElementRef, Renderer2, ViewChild } from '@angular/core';
import { myService } from 'src/app/myService/service';

@Directive({
  selector: '[mId]'
})
export class IdDirective {
  @ViewChild('identifier') mId: ElementRef;

  constructor(private renderer: Renderer2, private myService: Service, private elementRef: ElementRef) {
    this.method();
  }

  method() {
    this.service.getId().subscribe((response) => {
      const p = this.renderer.createElement('p');
      const text = this.renderer.createText('ID: ' + response.id);
      console.log(response.id);

      this.renderer.appendChild(p, text);
      this.renderer.appendChild(this.elementRef.nativeElement, p);
    });
  }

}

Te result is that the id number is placed inside the <header> tags of the layout at the bottom something like:

<header mId id="navbar">
      <h1 id="logo">...</h1>
      .
      .
      .
      <div #identifier class="mid"></div>
      .
      .
      .
      <p>ID: 1</p>
</header>

and I need that the final result be:

<header mId id="navbar">
      <h1 id="logo">...</h1>
      .
      .
      .
      <div #identifier class="mid">
           <p>ID: 1</p>
      </div>
</header>

Could anyone have an idea how could I do that or what I am doing wrong?

1

There are 1 best solutions below

0
On

To get the "identifier", you should use ContentChild, not ViewChild, but you only can used after ViewInit or in a setTimeout to give time to Angular to get the value

  @ContentChild('identifier') mId: ElementRef;

  constructor(private renderer: Renderer2, private elementRef: ElementRef) {
      setTimeout(()=>{
        this.method();
      })
  }

  method() {
    this.service.getId().subscribe((response) => {
      const response={id="currentID"} 
      const p = this.renderer.createElement('p');
      const text = this.renderer.createText('ID: ' + response.id);

      this.renderer.appendChild(p, text);
      this.renderer.appendChild(this.mId.nativeElement, p);

      this.renderer.setAttribute(this.mId.nativeElement,"id",response.id)
    })
  }