Search code examples
angular5web-componentpolymer-3.x

Import Polymer 3 component into Angular 5 project


I'm starting with polymer 3 and i'm working on this tutorial https://www.polymer-project.org/1.0/start/first-element/step-5, so basically i have the component js file as follows

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);

Now I'm wondering how to import this and use it in an angular 5 app.


Solution

  • Generate a new Angular app.

    ng new with-polymer
    

    From within with-polymer create a directory to store the web components in.

    mkdir src/app/components
    

    Copy your polymer component code to src/app/components/icon-toggle.js

    Install the polymer dependencies.

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

    Update src/app/app.module.ts to import CUSTOM_ELEMENTS_SCHEMA and tell NgModule that custom elements will be in use.

    import { CUSTOM_ELEMENTS_SCHEMA, NgModule } from '@angular/core';
    
    @NgModule({
      ...
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
    

    Import icon-toggle in src/app/app.module.ts.

    import './components/icon-toggle';
    

    Add an icon-toggle to src/app/app.component.html.

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

    Start up the dev server.

    npm start
    

    Note that you will probably want to include some web component polyfills.