角度动态组件的自定义标签名称

时间:2018-10-25 02:18:03

标签: html angular angular-components angular-dynamic-components

我有一个简单的组件

@Component({
  selector: '[my-component]',
  template: `<i>1</i><p>content</p><b>2</b>`
})
export class MyComponent {
  public tagName: string;
}

另一个实例化第一个实例的

export class AppComponent implements OnInit {
 @ViewChild("myContainer", { read: ViewContainerRef }) container;

  constructor(
      private viewContainer: ViewContainerRef,
      private resolver: ComponentFactoryResolver) {
  }

  ngOnInit() {
    this.container.clear();
    const compFactory = this.resolver.resolveComponentFactory(MyComponent);
    const componentRef = this.container.createComponent(compFactory);
    componentRef.instance.tagName = 'span';
  }
}

AppComponent的模板就是

<template #myContainer></template>

,所以输出是

<div my-component><i>1</i><p>content</p><b>2</b></div>

我要做的是在实例化期间自定义MyComponent模板,并将其p标记替换为名称应为tagName的标记。我知道在执行MyComponent方法时在AppComponent.ngOnInit创建之前的标记名称。

我要解决的另一个任务是MyComponent包装标签名称的自定义。将<div my-component>...替换为<span my-component>...,其中“ span”是所需的标签名称,在AppComponent.ngOnInit也是如此。

因此可以以编程方式提供这种自定义并获得关注:

<span my-component><i>1</i><span>content</span><b>2</b></span>

tagName可以是任何允许的HTML标记,并且不能选择ngIf / Switch。我已创建了用于快速潜水的演示:https://stackblitz.com/edit/angular-zngyoa

1 个答案:

答案 0 :(得分:1)

对于问题1,使用字符串regex将其替换为'span'标签的'p'。应该在ngAfterViewInit生命周期方法内完成。

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

@Component({
  selector: '[my-component]',
  template: `<i>1</i><p>content</p><b>2</b>`
})
export class MyComponent implements AfterViewInit, OnInit{
  public tagName: string;

  constructor(private elementref: ElementRef){}

  ngOnInit(){}

  ngAfterViewInit(){
    if(this.tagName && this.elementref){
      let htmlcontent = this.elementref.nativeElement.innerHTML;
      htmlcontent = htmlcontent.replace(/p/g, 'span');
      this.elementref.nativeElement.innerHTML = htmlcontent;
    }
  }
}