gpt4 book ai didi

angular - 动态更改标签? Angular 2

转载 作者:太空狗 更新时间:2023-10-29 17:24:45 25 4
gpt4 key购买 nike

有没有办法改变这个:

<div>Some text here</div>

收件人:

<tr>Some text here</tr>

将标签DIV标签动态更改为TR标签?基本上替换标签?

最佳答案

您可以创建自定义结构指令来执行此操作。

Online demo here

replace-tag.directive.ts

import { Directive, Input, TemplateRef, ViewContainerRef, ElementRef, AfterViewChecked } from '@angular/core';

@Directive({
selector: '[replaceTag]'
})
export class ReplaceTagDirective implements AfterViewChecked {
constructor(
private templateRef: TemplateRef<any>,
private vcf: ViewContainerRef
) { }
private _tag: string;
private _needUpdate: boolean = false;

@Input('replaceTag')
set tag(t: string): void {
this._tag = t;
this._needUpdate = true;
this.vcf.clear();
let template = this.templateRef.elementRef.nativeElement.nextElementSibling;
if (template) {
this.templateRef.elementRef.nativeElement.parentNode.removeChild(template);
}
this.vcf.createEmbeddedView(this.templateRef);
}

ngAfterViewChecked() {
if (this._needUpdate) {
this._updateTemplate();
this._needUpdate = false;
}
}

private _updateTemplate() {
let template = this.templateRef.elementRef.nativeElement.nextElementSibling;
if (template) {
let r = document.createElement(this._tag);
r.innerHTML = template.innerHTML;
this.templateRef.elementRef.nativeElement.parentNode.replaceChild(r, template);
}
}
}

app.component.ts

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

@Component({
selector: 'app-root',
template: `
App
<span *replaceTag="tag">
<strong>content {{ tag }} </strong>
<em>{{ message }}</em>
</span>
`
})
export class AppComponent implements OnInit {
tag: string = 'div';
timeOut: number = 2;

get message(): string {
return this.timeOut? `<- this tag will change after ${this.timeOut} seconds.` : 'done';
}

ngOnInit() {
setTimeout(() => {
this.tag = 'h2';
this.timeOut = 4;
}, 2000);

setTimeout(() => {
this.tag = 'sub';
this.timeOut = 0;
}, 4000);
}
}

关于angular - 动态更改标签? Angular 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com