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 内容并插入到元素中。最后将自定义元素添加到页面中,即可解决该问题。

相关内容

热门资讯

透视安卓版!wepoker辅助... 透视安卓版!wepoker辅助器怎么弄,wepoker挂(透视)微扑克教程(有挂教程)1、wepok...
透视教程!wepoker私人局... 透视教程!wepoker私人局有透视吗,wepoker作弊方法(透视)软件教程(有挂解密);一、we...
透视模拟器!wepoker有辅... 透视模拟器!wepoker有辅助功能吗,wepokerplus万能挂(透视)介绍教程(有挂介绍);w...
透视脚本!wepokerplu... 透视脚本!wepokerplus透视脚本免费,wepoker怎么获得好牌(透视)2025新版技巧(有...
透视脚本!wepoker底牌透... 透视脚本!wepoker底牌透视,wepoker透视方法(透视)第三方教程(有挂辅助);进入游戏-大...
透视数据!wepoker-h5... 透视数据!wepoker-h5下载,wepoker私局代打(透视)高科技教程(有挂工具)1、下载好w...
透视总结!wepokerplu... 透视总结!wepokerplus辅助,wepoker有插件吗(透视)存在挂教程(有挂辅助)1、这是跨...
透视安装!购买wepoker模... 透视安装!购买wepoker模拟器,wepoker免费脚本(透视)力荐教程(有挂插件)一、购买wep...
透视黑科技!wepoker有插... 透视黑科技!wepoker有插件吗,wepoker私人局透视插件(透视)细节揭秘(有挂工具);1、起...
透视有挂!wepoker到底有... 透视有挂!wepoker到底有没有透视,wepoker破解工具(透视)线上教程(有挂攻略);wepo...