如何在ts中使用变量作为HTML文件中的标记名? [英] How to use a variable in ts as a tagname in a HTML file?

查看:534
本文介绍了如何在ts中使用变量作为HTML文件中的标记名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以使用通过变量获取的 HTML标记名称(例如< p>)?

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?

以下是我尝试的代码:

app.component.ts

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

app.component.html

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

如果我尝试这样做:

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

我遇到类似

模板解析错误:意外的结束标记"{{tagName}}".如果该标签已经被另一个标签关闭,则可能会发生这种情况.

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:你们中的许多人建议使用innerHTML,但这在内容较小的情况下是可行的.在我的典型情况下,我想将所有html内容都放在同一个文件中,并且会得到 ts 文件中的标记名称

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

推荐答案

首先,这种方法无法正常工作,因为插值会将值视为字符串,因此它将始终在屏幕上显示为文本.

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.

根据您的问题,我了解的是您想在现有元素中添加HTML.

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

最简单的方法是:-

在ts中为变量提供要插入的值,例如.

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

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

,然后在您的html中只需执行以下操作:-

and then in your html you can simply do:-

<h1 [innerHTML]="tagName">

另一种方法是在ts中获取元素的引用,然后从其中插入

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

这篇关于如何在ts中使用变量作为HTML文件中的标记名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆