加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

动态更改标签? Angular 2

发布时间:2020-12-17 10:17:09 所属栏目:安全 来源:网络整理
导读:无论如何要改变这个: divSome text here/div 至: trSome text here/tr 动态地将标签DIV标签更改为TR标签?基本上替换标签? 您可以创建自定义结构指令来执行此操作. Online demo here 更换-tag.directive.ts import { Directive,Input,TemplateRef,ViewCon
无论如何要改变这个:
<div>Some text here</div>

至:

<tr>Some text here</tr>

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

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

Online demo here

更换-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);
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读