Enthu
Enthu

Reputation: 532

To render each of the element of a string in a new line using Angular4 renderer

create() {
 this.tooltip = this.renderer.createElement('div');
 this.renderer.appendChild( 
 this.tooltip,this.renderer.createText(this.tooltipTitle);
);

this.renderer.appendChild(document.body, this.tooltip);

Eg: In my application

this.tooltipTitle = "Apple,Ball,Cat,Dog,Elephant"

Expected Result

Apple 
Ball
Cat
Dog

Upvotes: 0

Views: 637

Answers (2)

SiddAjmera
SiddAjmera

Reputation: 39432

Give this a try:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  tooltipTitle = "Apple,Ball,Cat,Dog,Elephant";
  tooltip: HTMLElement;

  constructor(private renderer: Renderer2) { }

  ngOnInit() {
    this.create();
  }

  create() {
    // creating the array
    let titles = this.tooltipTitle.split(",")
    // append each val of the resulting array to the tooltip
    titles.forEach(title => {
      const p = this.renderer.createElement('p');
      this.renderer.appendChild(
        p,
        this.renderer.createText(title),
      );
      this.renderer.appendChild(document.body, p);
    });

  }
}

UPDATE:

You can also create a <br> tag after the text and align it more to your current code. Something like this:

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  tooltipTitle = "Apple,Ball,Cat,Dog,Elephant";
  tooltip: HTMLElement;

  constructor(private renderer: Renderer2) { }

  ngOnInit() {
    this.create();
  }

  create() {
    this.tooltip = this.renderer.createElement('div');
    this.tooltipTitle.split(',').forEach((text) => {
      this.renderer.appendChild(this.tooltip, this.renderer.createText(text));
      this.renderer.appendChild(this.tooltip, this.renderer.createElement('br'));
      this.renderer.appendChild(document.body, this.tooltip);
    });

  }
}

Here's an Updated Working Sample StackBlitz for your ref.

Upvotes: 2

jonatjano
jonatjano

Reputation: 3738

!!! note that my answer may need correction: I didn't use Angular for so long I forgot most of it !!!

but my answer will give you an hint on how to do:

I think making an array of your title may help

create() {
  this.tooltip = this.renderer.createElement('div');

  // creating the array
  let titles = this.tooltipTitle.split(",")

  // append each val of the resulting array to the tooltip
  titles.forEach(title => {
    this.renderer.appendChild( 
      this.tooltip,
      this.renderer.createText(title);
    );
  });

  this.renderer.appendChild(document.body, this.tooltip);
}

Upvotes: 0

Related Questions