首页 > 解决方案 > 如何通过使用 innerHTML 添加组件来呈现组件?

问题描述

我有一个组件 A ,它只包含一个带有 id 的 div 和一个使用 interHTML 在 div 内呈现组件的按钮document.getElementById('my-router-outlet').innerHTML = '<app-component-b-page></app-component-b-page>';。但这不是渲染我想知道为什么?

我试图避免使用 ngIf 作为选择器,出于性能原因应该为其呈现组件。另外,如果我清除 innerHTML 是否会清除该组件的资源?

标签: htmlangular

解决方案


好的,这里有几件事

  1. innerHTML = '<app-component-b-page></app-component-b-page>'永远不会工作,角度不会从innerHTML调用中识别角度组件标签

  2. 使用*ngIf不会影响页面的性能,所以执行以下操作

<app-component-b-page *ngIf="value === true"></app-component-b-page>

可能是你最好的选择

  1. 如果你真的不想使用*ngIf你可以使用@ViewChildComponentFactoryResolver

在您的 HTML 中

<!-- this is where your component will be rendered -->
<div #entry></div>

在您的组件中

import { Component, OnInit, ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core'
import { YourComponent } from ... // import the component you want to inject 
// ...

export class ...
  @ViewChild('entry', {read: ViewContainerRef, static: true }) entry: ViewContainerRef;

  constructor(
    private _resolver: ComponentFactoryResolver
  ) {}

  showComponent() {
     const factory = this._resolver.resolveComponentFactory(YourComponent);
     // this will insert your component onto the page
     const component = this.entry.createComponent(factory);
  }

  // and if you want to dynamically remove the created component you can do this

  removeComponent() {
     this.entry.clear();
  }


推荐阅读