我正在尝试创建一个 UI 套件作为可重用的 Web 组件(使用 Angular 元素)。我做了一个测试运行,看看我们在 Angular 项目中开发的自定义元素是否也可以在该 Angular 项目中使用(简单来说,我想为 UI 套件创建一个类似页面的文档 + 我如何测试我正在开发的 UI 组件 - 在同一项目内)。
这是 stackblit 的链接 https://stackblitz.com/edit/angular-elements-test-kavinda
我使用了一个名为“按钮模块”的单独模块来开发 ui 组件,并且自定义元素定义也在该模块中完成。我尝试在 app-component.html 中使用这些元素 - 但没有成功。
Primary-btn-component.html
<button>
<slot name="icon_left" class="icon_left"></slot>
<slot name="btn_text" class="btn_text"></slot>
<slot name="icon_right" class="icon_right"></slot>
</button>
用于定义自定义元素的代码
const btnElem = createCustomElement(PrimaryBtnComponent, { injector: this.injector });
customElements.define('primary-btn', btnElem);
然后在 app-component.html 中使用该元素,如下所示
<primary-btn>
<span slot="btn_text">Button</span>
</primary-btn>
最佳答案
创建一个没有应用程序的项目
ng new my-lib --create-application=false
然后添加一个库
ng generate library my-lib
然后添加一个使用该库的演示应用程序
ng generate application my-lib-demo
本文中有详细步骤。
https://nezhar.com/blog/up-and-running-library-development-with-angular-7/
关于angular - 在同一 Angular 项目中使用 Angular 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142136/