Skip to content

Instantly share code, notes, and snippets.

@rjcorwin
Last active January 1, 2023 11:43
Show Gist options
  • Save rjcorwin/de3263862c280a1df1b0648ab5d6cd25 to your computer and use it in GitHub Desktop.
Save rjcorwin/de3263862c280a1df1b0648ab5d6cd25 to your computer and use it in GitHub Desktop.
Directions on how to use Lit Element as a replacement to `@angular/core`'s `Component` decorator.

How to use Lit Element in an Angular Project

Directions

  1. In tsconfig.json, set "target" to "es6".
  2. Add schemas: [ CUSTOM_ELEMENTS_SCHEMA ], in the NgModule decorator of the Angular Module where your components will live.
  3. Use Angular CLI to generate a component.
  4. Refactor generated Component's import statement, decorator, constructor, and add a render function as seen in the example below.
  5. Refactor the import statement of the Component in the parent Module from import { HelloWorldComponent } from './hello-world/hello-world.component' to import './hello-world/hello-world.component'
// helo-case/hello-case.component.ts

import {
  LitElement,
  html,
  property,
  customElement,
} from '@polymer/lit-element';

@customElement('app-hello-world')
export class HelloWorldComponent extends LitElement {

  constructor() {
    super()
  }
  
  @property() firstName;

  @property() lastName;

  render() {
    return html`
      <h1>Hello ${this.firstName} ${this.lastName}</h1>
    `;
  }
  
}
// hello-world.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { CommonModule } from '@angular/common';
import './hello-world/hello-world.component'

@NgModule({
  schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
  imports: [
    CommonModule
  ],
  declarations: [
    // HelloCaseComponent // We can't do this yet :(
  ]
})
export class HelloWorldModule { }

Limitations

  • Angular will fail if you declare a Lit Element based Component in a Module thus you cannot expect Angular to inject services into your Lit Element based Component constructors.
  • Because of a bug in the current version of Webpack that Angular CLI uses, you can only target ES6 builds, thus support for older browsers is not currently possible. This may be fixed when Angular 8 is released.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment