0

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!

4
  • Why would you want to do this? Commented Dec 25, 2018 at 5:14
  • You have already applied bg-color class to ptag, what you want? Commented Dec 25, 2018 at 5:18
  • Because I want to dynamically generate elements and add come styling to it. stackblitz.com/edit/angular-4iz6cg Commented Dec 25, 2018 at 5:26
  • If anyone want's to edit please fork and edit the code Commented Dec 25, 2018 at 5:36

2 Answers 2

1

It is not working because you are not appending the correct element to the DOM.

Do this instead:

this.renderer2.appendChild(this.messages.nativeElement, pTag);

https://stackblitz.com/edit/angular-gkcpw7?file=src%2Fapp%2Fapp.component.ts

Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to use the renderer, Use template binding

<div>
  <p *ngIf="condition" class="{{bgClass}} another-static-class"> {{ data?.message }} </p>
</div>

Component code

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  bgClass: string;
  data = { message: 'WELCOME' };
  condition = false;

  ngOnInit() {
    this.condition = true;
    this.bgClass = 'bg-color';
  }
}

Fixed stackblitz

1 Comment

But my goal is to achieve something different.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.