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?
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