2

I want to know if there is any way to use the HTML tag name (<p> for e.g.) which is obtained from a variable?

The following is the code I tried:

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
  name = 'Angular';
  somevalues = [1, 2, 3, 4, 5]
  tagName;
  getFromCharCode(index) {
    return String.fromCharCode('A'.charCodeAt(0) + index);
  }
  ngOnInit(){
    this.tagName = "p";
  }
}

app.component.html

<div *ngFor="let x of somevalues; let i = index">
  {{x}} - {{i}}
  {{ getFromCharCode(i) }}
  <h1>{{tagName}}
  </h1>
</div>

If I tried like:

<{{tagName}}></{{tagName}}>

I'm getting error like

Template parse errors: Unexpected closing tag "{{tagName}}". It may happen when the tag has already been closed by another tag.

I referred to this, but I find it is pretty complex for a simple replacement. Is there any other way to achieve this?

EDIT-1: Many of you suggest to use innerHTML but that would be feasible incase of small contents. In my typical case, I would like to have all my html content in the same file and I would get only the name of the tag in ts file

Dharman
  • 30,962
  • 25
  • 85
  • 135
Krishna Prashatt
  • 631
  • 9
  • 18
  • Please see https://stackoverflow.com/questions/31548311/angular-html-binding – Blake Mumford Sep 24 '19 at 06:43
  • @BlakeMumford, thanks for the dupe but still I am confused, the inner HTML method will work if I have the entire content in the variable. But thats not the case here. I have only the tag name and the content inside tag is hardcoded in HTML file itself. – Krishna Prashatt Sep 24 '19 at 06:48
  • You might want to include an example of the HTML that you want to display because I'm finding it difficult to understand what it is that you want to do. – Blake Mumford Sep 25 '19 at 01:14

3 Answers3

1

You can use innerHTML for this:

ngOnInit(){
  this.tagName = "<p></p>";
}

<div [innerHTML]="tagName"></div>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
1

Hi first of all this way will not work as the interpolation considers the value as a string so it will always appear as a text on the screen.

By your question what i understand is you want to add HTML inside an already existing element.

The easiest way way would be: -

in your ts give your variable the value that you want to insert so eg.

tagName = `<div> Some text inside </div>`;

and then in your html you can simply do:-

<h1 [innerHTML]="tagName">

other way to do this would be to get the reference of the element in ts and insert it from there

Akshay Bhat
  • 284
  • 1
  • 10
0

Try this one

<div *ngFor="let x of somevalues; let i = index">
  {{x}} - {{i}}
  {{ getFromCharCode(i) }}
  <h1 innerHtml="<{{tagName}}></{{tagName}}>"></h1>
</div>
yoosuf
  • 29
  • 3