Web Components in Angular.js

Web components are a way of creating custom elements that will work with the standard HTML elements. We know what web components are. It is a set of features that gives a standard component model for the web allowing for encapsulation and interoperability of HTML components. Angular is a good option for client-side applications since it has a robust API which has best Web Component support. First install angular cli and create new applications. Then run ng serve command to run Angular application on localhost:4200. Install our drop-down component install test web component by running below given command.

npm install web-component-essentials.

Now components are installed in our project and add an entry into package.json. 


import { BrowserModule } from '@angular/platform-browser';

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

import 'web-component-essentials';


import { AppComponent } from './app.component';


@NgModule({

  declarations: [AppComponent],

  imports: [BrowserModule],

  providers: [],

  bootstrap: [AppComponent],

  schemas: [

    CUSTOM_ELEMENTS_SCHEMA // Tells Angular we will have custom tags in our templates

  ]

})

export class AppModule {}

Add CUSTOM_ELEMENTS_SCHEMA from @angular/core to the application module. It tells Angular that we will be using custom elements which are not registered Angular components in our app.

 import { Component } from '@angular/core';


@Component({

  selector: 'app-root',

  templateUrl: './app.component.html',

  styleUrls: ['./app.component.css']

})

export class AppComponent {

  myTitle = 'project-angular';

  open = false;


  toggle(event) {

    console.log(event);

    this.open = event.detail;

  }

}

We have two properties in our application. The myTitle will be passed to the drop-down and the open property to track if drop-down is open or closed. We have a method called toggle() which will be called whenever the drop-down is closed or opened. This is the app.component.html file.

<h1>Angular Application using Web Components</h1>


<p>

  {{open ? 'open' : 'closed'}}

</p>


<x-dropdown [title]="myTitle" (show)="toggle($event)">

  Hello from Web Component in Angular!

</x-dropdown>

Depending on the value of open property Angular expression displays a message open or closed.