原文: https://medium.com/@jorgecasar/how-to-use-web-components-with-angular-41412f0bced8
-------------------------------------------------------------
Custom Elements Everywhere, Angular passes all the tests so it is a good candidate to implement the use of Web Components.
jorgecasar/tutorial-webcomponents-angular repository.
ng new tutorial-webcomponents-angular and open it in our favorite editor.
src/app/app.module.ts:
export class AppModule { }
Adding polyfills
webcomponents polyfills.
First, install the dependency using NPM:
npm install --save @webcomponents/webcomponentsjs
angular.json file:
}
index.html.
And finally we must wait for the dependencies to load to start our app and thus make sure that the Web Components are ready to be used:
if (window.WebComponents.ready) {
// Web Components are ready
bootstrapModule();
} else {
// Wait for polyfills to load
window.addEventListener('WebComponentsReady', bootstrapModule);
}
ES5 Support
<head>, just before the webcomponents script included before.
</div>
With this we have our app ready to include Web Components, so let’s create one and check its compatibility.
Creating a Web Component
Justin Fagnani.
npm i --save @polymer/lit-element
wc-mood:
customElements.define('wc-mood', WebComponentsMood);
app.component.ts:
import './wc-mood/wc-mood';
And we use it in the html of our component:
<my-element mood=”awesome”></my-element>
Testing the interaction with the Web Component
Now that we have the Web Component working, let’s try the interaction with it.
Set properties from Angular
randomMood method that changes that property:
this.moods[index];
}
}
And we make the corresponding change in the html to establish the property and we make that by clicking on the Angular logo we establish another value to the property:
Listen to events from Angular
To complete the interaction, we will launch an event from the component to listen to it from Angular.
In the Web Component we will notify the changes in the properties sending the event:
this.dispatchEvent(
new CustomEvent(prop + '-changed', {
detail: { value: _changedProps[prop] }
})
);
}
}
mood. We do this because it is the most logical from my point of view and also both Angular and Polymer use this pattern, so we can begin to standardize it ????
Once we have made this change we can already hear the event from Angular. To verify that angular receives the event we will animate the Angular logo for 1 second using the following method:
this.isChanged = false, 1000);
}
animated class to the image:
Two-way data binding
To crown things off and simplify the way to establish and listen to the event we can use the double data binding:
moodChanged method when the value changes:
this.moodChanged();
}
}
Demo
For you to see the operation here I leave the demo:
https://tutorial-webcomponents-angular.firebaseapp.com/