【问题标题】:Import Polymer 3 component into Angular 5 project将 Polymer 3 组件导入 Angular 5 项目
【发布时间】:2018-05-22 11:50:25
【问题描述】:

我从聚合物 3 开始,我正在编写本教程 https://www.polymer-project.org/1.0/start/first-element/step-5,所以基本上我的组件 js 文件如下

icon-toggle.js

import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/iron-icon/iron-icon.js';

class IconToggle extends PolymerElement {
  static get template() {
    return html`
      <style>
        /* shadow DOM styles go here */
        :host {
          display: inline-block;
          --icon-toggle-color: lightgrey;
          --icon-toggle-outline-color: black;
          --icon-toggle-pressed-color: red;
        }
        iron-icon {
          fill: var(--icon-toggle-color, rgba(0,0,0,0));
          stroke: var(--icon-toggle-outline-color, currentcolor);
          cursor: pointer;
        }
        :host([pressed]) iron-icon {
          fill: var(--icon-toggle-pressed-color, currentcolor);
        }
      </style>
  
      <!-- shadow DOM goes here -->
      <iron-icon icon="[[toggleIcon]]"></iron-icon>

    `;
  }
  static get properties() {
    return {
      pressed: {
        type: Boolean,
        value: false,
        notify: true,
        reflectToAttribute: true
      },
      toggleIcon: {
        type: String
      }
    };
  }
  constructor() {
    super();
    this.addEventListener('click', this.toggle.bind(this));
  }
  toggle() {
    this.pressed = !this.pressed;
  }
}

customElements.define('icon-toggle', IconToggle);

现在我想知道如何导入它并在 Angular 5 应用程序中使用它。

【问题讨论】:

  • 将其作为模块导入index.html 并将标签放置在页面中的任何位置。如果您想将它放在任何组件中,请查看 ngmodule 的 entryComponents:[]

标签: angular5 web-component polymer-3.x


【解决方案1】:

生成一个新的 Angular 应用。

ng new with-polymer

with-polymer 中创建一个目录来存储 Web 组件。

mkdir src/app/components

将您的聚合物组件代码复制到src/app/components/icon-toggle.js

安装聚合物依赖项。

npm install @polymer/iron-icon @polymer/polymer

更新 src/app/app.module.ts 以导入 CUSTOM_ELEMENTS_SCHEMA 并告诉 NgModule 自定义元素将被使用。

import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';

@NgModule({
  ...
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})

src/app/app.module.ts 中导入icon-toggle

import './components/icon-toggle';

icon-toggle 添加到src/app/app.component.html

<icon-toggle toggle-icon="star"></icon-toggle>

启动开发服务器。

npm start

请注意,您可能希望包含一些 web component polyfills

【讨论】:

    猜你喜欢
    • 2018-09-21
    • 1970-01-01
    • 2018-09-27
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 2018-04-17
    相关资源
    最近更新 更多