DEV Community

Marko Berger
Marko Berger

Posted on

The Angular (elements) gift to the Web

Intro in Angular Elements

Imagine that your client wants to sell her or his service on the third-party web app. You then have to somehow integrate your service on their application or redirect to your application. That is not an easy job to and user experience is awful. So how does Angular Elements helps us with that? Did you hear about Web Component Technology?

Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps.

This tech was introduced in 2011 by Alex Russell at Fronteers Conference.
And now Angular found the way to introduce this tech into his own environment.
Let’s see what documentation says.

Angular elements are Angular components packaged as custom elements, a web standard for defining new HTML elements in a framework-agnostic way.

Cool right!

Enough talk lets code.
We will create element registration-form

npm install -g @angular/cli 
ng new registration-form
ng add @angular/elements project=registration-form

@angular/elements are a package that contains all the good stuff we need for creating Angular elements. It contains document-register-element a lightweight version of the W3C Custom Elements specification. Remember Angular Elements are still young. So there are still some issues. One of them is that you need to change the document-register-element version from 1.7.2 to 1.8.1 (change it in package.json and do npm install).

All the preps are done. Let's make our hands dirty.

First, generate the new component.

ng g c register-form

Registration-form.component.ts

@Component({
  selector: 'register-peeker',
  templateUrl: './register-peeker.component.html',
  styleUrls: ['./register-peeker.component.css'],
  encapsulation: ViewEncapsulation.Native
})

What is going on here?

We want to have isolated application inside of other application with our own CSS style. See the problem. To solve this. We are got to tell Angular to use Shadow Dom (encapsulation part of the code) to isolate our CSS styles and compile it into JavaScript. So that we can bundle it into one file. There are other ViewEncapsulation strategies but Native is one preferred.
Now you can do that nice Angular magic we all love inside component.ts, component.html, and component.css component files.
But if you want to use the same CSS styles of the "parent" page. Just switch encapsulation to None and remove styleUrls.
Let’s fast forward to the place where the real the magic happens the app.module.ts.

Top comments (0)