Is there anyway to change this:
Some text here
To:
Some text here
you could create custom structure directive to do this.
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,
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
content {{ tag }}
{{ message }}
`
})
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);
}
}