Integrating with Angular

Now, let's say we have a component called app-main-body built using Angular (file: main-body.component.ts) that looks something like this:

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

@Component({
selector: 'app-main-body',
templateUrl: './main-body.component.html',
styleUrls: ['./main-body.component.css']
})
export class MainBodyComponent implements OnInit {
src: string ;
altText: string;

constructor() {
this.src = 'https://www.freewebheaders.com/wordpress/wp-content/gallery/clouds-sky/clouds-sky-header-2069-1024x300.jpg';
this.altText = 'Blue Clouds';
}

ngOnInit() {

}
}

If we want to include the <header-image> web component here, we can simply add the following code:

...
import HeaderImage from '../web-components/header-image/header-image.js';

...
export class MainBodyComponent implements OnInit {
...
...

ngOnInit() {
customElements.define('header-image', HeaderImage);
}

}

Here, we are simply importing the component definition, and then inside the ngOnInit() callback method, we are registering the custom element. If we look at the template file, main-body.component.html, the web component can be included as shown in the following code:

<p>
main-body works!
</p>
<header-image attr.src={{src}} attr.alttext="{{alttext}}"></header-image>

Here, we are passing in src as well as altText to the <header-image> component as attribute values. In this way, we can have Web Components built outside of Angular for use in Angular projects.

Now that we know how a Vanilla Web Component can be used in Angular projects, let's look at how Web Components can be used in Vue components.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.108.9