问题
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
回答1:
You can use innerHTML for this:
ngOnInit(){
this.tagName = "<p></p>";
}
<div [innerHTML]="tagName"></div>
回答2:
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
回答3:
Try this one
<div *ngFor="let x of somevalues; let i = index">
{{x}} - {{i}}
{{ getFromCharCode(i) }}
<h1 innerHtml="<{{tagName}}></{{tagName}}>"></h1>
</div>
来源:https://stackoverflow.com/questions/58074266/how-to-use-a-variable-in-ts-as-a-tagname-in-a-html-file