AngularElements使用ng-content无法工作
创始人
2024-10-24 17:01:01
0

当使用 Angular Elements 时,如果在组件中使用了 ng-content,可能会遇到组件不工作的问题。这是因为 Angular Elements 不支持通过 ng-content 创建内容。解决这个问题的方法是通过编写自定义的 DOM 选择器来手动获取内容,然后将它们插入组件中。

以下是使用自定义 DOM 选择器解决问题的代码示例:

import { Component, Injector, OnInit, Input } from '@angular/core';
import { createCustomElement } from '@angular/elements';

@Component({
  selector: 'app-custom-element',
  template: ''
})
export class CustomElementComponent implements OnInit {
  @Input() inputProp: string;

  constructor(private injector: Injector) {}

  ngOnInit() {
    const content = this.getContent();
    const customElement = createCustomElement(
      CustomElementComponent,
      { injector: this.injector }
    );
    customElements.define('app-custom-element', customElement);
    const element = document.createElement('app-custom-element');
    element.appendChild(content);
    document.body.appendChild(element);
  }

  private getContent() {
    const slot = document.createElement('slot');
    slot.setAttribute('name', 'content');
    return slot;
  }
}

这个组件利用 createCustomElement() 函数创建自定义元素,然后在 ngOnInit() 生命周期钩子函数中手动获取 ng-content 内容并插入到元素中。最后将自定义元素添加到页面中,即可解决该问题。

相关内容

热门资讯

开挂辅助下载"pok... 开挂辅助下载"pokemmo辅助器"开挂(透视)辅助下载(竟然有挂);无需打开直接搜索加薇13670...
开挂辅助平台"德州局... 开挂辅助平台"德州局怎么透视"开挂(透视)辅助脚本(有挂头条)您好:德州局怎么透视这款游戏可以开挂,...
开挂辅助安装"德普之... 大家好,今天小编来为大家解答德普之星透视辅助这个问题咨询软件客服可以免费测试直接加微信(136704...
开挂辅助安装"hhp... hhpoker软件可以玩吗开挂教程视频分享装挂详细步骤在当今的网络游戏中,hhpoker软件可以玩吗...
开挂辅助脚本"wep... wepoker轻量版辅助 无需打开直接搜索微信:136704302本司针对手游进行,选择我们的四大理...
开挂辅助插件"hh ... hh poker软件开挂教程视频分享装挂详细步骤在当今的网络游戏中,hh poker软件作为一种经典...
开挂辅助脚本"aap... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
开挂辅助安装"wep... 开挂辅助安装"wepoker有透视功能吗"开挂(透视)辅助插件(有挂存在) 了解更多开挂安装加(13...
开挂辅助安装"pok... 您好:pokemmo脚本手机版这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多...
开挂辅助插件"wep... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...