gpt4 book ai didi

html - Angular 2。如何在模板中打印来自 @Input() 参数的 HTML 标签?

转载 作者:行者123 更新时间:2023-11-27 23:10:12 25 4
gpt4 key购买 nike

想法:

<h2 *ngIf="tag == 'h2'"></h2>
<h3 *ngIf="tag == 'h3'"></h3>
<p *ngIf="tag == 'p'"></p>

我想得到 tag是动态的,具体取决于标签属性值。tag是一个 Input()参数

P.S.:我尝试过: <{{tag}></{{tag}}> , 但它给出错误并且不起作用

<div (mouseenter)="setEditMode()" [innerHTML]="result | safeHtml" *ngIf="!editMode"></div>
<div (mouseleave)="setViewModeIfNotFocused()" *ngIf="editMode">
<input type="text" [(ngModel)]="content" #inputEl>
</div>

-

import { Component, Input, OnInit, ViewChild } from '@angular/core';
@Component({
selector: 'ui-edit-field',
templateUrl: 'edit-field.component.html'
})
export class UiEditFieldComponent implements OnInit {

@ViewChild('inputEl')
public inputEl: any;

@Input('tag')
public tag: string;

@Input('classes')
public classes: string;

@Input('content')
public content: string;

public result: string;

public editMode = false;

constructor() {
}

ngOnInit() {
this.result = '<' + this.tag + ' class="' + this.classes + '">' + this.content + '</' + this.tag + '>';
}

setEditMode() {
this.editMode = true;
}

setViewModeIfNotFocused() {
if (true) {
this.editMode = false;
}
}
}

最佳答案

你可以使用

<div [outerHTML]="tag"></div>

但是tag需要包含 <...> , 因为它们不能添加到模板中。

如果tag应该成为 Angular 组件,那么你需要一种不同的方法。上述方法只允许添加 HTML 而没有任何 Angular 功能。

另见 https://stackoverflow.com/a/41089093/217408

更新

_content:string;
@Input('content')
public set content(val:string) : void { this._content = val; updateContent();}

ngOnInit() {
this._updateContent();
}

_updateContent() {
this.result = '<' + this.tag + ' class="' + this.classes + '">' + this._content + '</' + this.tag + '>';
}

关于html - Angular 2。如何在模板中打印来自 @Input() 参数的 HTML 标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46522441/

25 4 0