I'm trying to add a class to the dynamically created element in Angular
sample-dom-manipulation.component.ts
import { Component, OnInit, ViewChild, ElementRef, Renderer2 } from '@angular/core';
@Component({
selector: 'app-sample-dom-manipulation',
templateUrl: './sample-dom-manipulation.component.html',
styleUrls: ['./sample-dom-manipulation.component.css']
})
export class SampleDomManipulationComponent implements OnInit {
@ViewChild('divMessages', {read: ElementRef}) private messages: ElementRef;
text;
constructor(private renderer2: Renderer2) {
}
ngOnInit() {
const data = {message: 'WELCOME'};
const pTag = this.renderer2.createElement('p');
this.text = this.renderer2.createText(data.message);
// append text to p element
this.renderer2.appendChild(pTag, this.text);
// I want to add the css-class to dynamically generated element!
// But below line of code is not working.
pTag.classList.add('bg-color');
this.renderer2.appendChild(this.messages.nativeElement, this.text);
// Below code works fine! but I don't want to do like this
// this.renderer2.addClass(this.messages.nativeElement, 'bg-color');
}
}
sample-dom-manipulation.component.html
<div #divMessages>
</div>
<p class="bg-color">
COLORS
</p>
Please find the Stack-Blitz link.
Thanks in advance!