动态更改标签?角度2 [英] Change a Tag Dynamically? Angular 2

查看:58
本文介绍了动态更改标签?角度2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正有什么可以改变的吗?

Is there anyway to change this:

<div>Some text here</div>

收件人:

<tr>Some text here</tr>

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

Change the tag DIV tag to TR tag dynamically? Basically Replace the Tags?

推荐答案

您可以创建自定义结构指令来做到这一点.

you could create custom structure directive to do this.

此处在线演示

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

这篇关于动态更改标签?角度2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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