Kako stvoriti prilagođene elemente i web komponente Kutnih 6

6 koraka za stvaranje kutnih elemenata pomoću Angular CLI

Kutni elementi su kutne komponente koje nose minificiranu verziju cijelog okvira. Omogućuju vam stvaranje prilagođenih elemenata (jedne od web komponenata) na okvirno agnostički način. Mogu se koristiti u jednostavnim web projektima, ali sa snagom Angulala.

Nakon čitanja službene dokumentacije za Kutne elemente shvatio sam da joj strukturirano nedostaje implementacijski dio. To je razlog zbog kojeg navodim korake za početak!

1. Instalirajte Angular CLI 6 i izradite novi projekt

npm i -g @angular/cli ng new angular-custom-elements

Kako je Angular uveo koncept prilagođenih elemenata u Angular 6, moramo imati instaliranu v6 ili noviju verziju. Također možete dodati --stylezastavicu da biste postavili zadano proširenje stila.

2. Dodajte paket elemenata

Prilagođeni elementi nisu u potpunosti implementirani u svim preglednicima. Stoga zahtijevamo Polyfills kako bi ih pokrenuli. S novom naredbom CLI ng addmožete dodati knjižnicu Angular i potrebna polifila:

ng add @angular/elements

3. Stvorite komponentu

Stvorimo komponentu koja će djelovati kao prilagođeni element do kraja ovog posta:

ng g component button --inline-style --inline-template -v Native

Koristimo ViewEncapsulation.Nativekako bismo spriječili da stilovi komponente iscure i utječu na druge elemente. To će našu komponentu prikazati u izvornoj implementaciji sjene DOM u pregledniku (v0; za v1 koju koristimo ViewEncapsulation.ShadowDOM) spajanjem svih stilova, predloška i koda klase komponente u jednu datoteku.

4. Dodajte svojstva komponenti

Nakon nekoliko promjena, komponenta gumba izgleda ovako:

Prema službenim dokumentima:

API za izradu analizira komponentu tražeći svojstva unosa i definira odgovarajuće atribute za prilagođeni element.

Transformira nazive svojstava kako bi ih učinila kompatibilnima s prilagođenim elementima, koji ne prepoznaju razlike u padežima. Dobiveni nazivi atributa koriste mala slova odvojena crticama. Na primjer, za komponentu s @Input('myInputProp') inputProp, odgovarajući prilagođeni element definira atribut '' my-input-prop”.

I također:

Izlazi komponenata šalju se kao prilagođeni HTML događaji, s imenom prilagođenog događaja koji odgovara nazivu izlaza.

Na primjer, za komponentu s @Output() valueChanged = new EventEmitter(), odgovarajući prilagođeni element otprema događaje s imenom "valueChanged". Emitirani podaci pohranit će se u detailsvojstvu događaja . Ako navedete alias, koristi se ta vrijednost. Na primjer,@Output('myClick') clicks = new EventEmitter gt;(); results in dispatch events with the name "myClick".

5. Update NgModule

Following are the major steps that need to be followed in app.module.ts:

  1. Remove the default bootstrap array which is set to AppComponent
  2. Since our ButtonComponent is not a part of any other component, and is also not a root of an Angular application, we need to tell Angular to compile it specifically. For this we put it on the entryComponents list. Otherwise Angular tree shaking will drop this component from the prod bundle.
  3. Add ngDoBootstrap() to tell Angular to use this module for bootstrapping.
  4. Angular provides the createCustomElement() function for converting an Angular component, together with its dependencies, to a custom element. The createCustomElement() function is expecting to get two parameter:
  • First, the Angular component which should be used to create the element.
  • Second, a configuration object. This object needs to include the injector property which is set to the current Injector instance.

5. The next step is to register the newly created custom element in the browser. This is done by calling customElements.define(). Please note that this is not Angular. The customElements read-only property belongs to the Window interface. It returns a reference to the CustomElementRegistryobject. This object can be used to register new custom elements. It can also get information about previously registered custom elements in the browser.

The customElements.define() method needs two parameter:

  • The first parameter is of type string and contains the name of the element. Passing the string ‘app-button’ means that the custom element on> will be registered and can be used in the HTML code.
  • The second parameter is the custom element which has been created before.

6. Now replace target value in tsconfig.json from es5 to es2015 as in browsers that support Custom Elements natively, the specification requires developers to use ES2015 classes to define Custom Elements.

6. Build and run

In order to build we will use a standard ng build command. But since it outputs four files (runtime.js , scripts.js, polyfills.js and main.js) and we’d like to distribute our component as a single js file, we need to turn hashing file names off. Let’s modify the scripts in package.json and add package entry:

"scripts": { …, "build": "ng build --prod --output-hashing=none", // For Windows: "package": "jscat ./dist/angular-custom-elements/runtime.js ./dist/angular-custom-elements/polyfills.js ./dist/angular-custom-elements/scripts.js ./dist/angular-custom-elements/main.js > custom-button-element.js", // For Mac or Linux: "package": "cat ./dist/angular-custom-elements/runtime.js ./dist/angular-custom-elements/polyfills.js ./dist/angular-custom-elements/scripts.js ./dist/angular-custom-elements/main.js > custom-button-element.js", …, }

Since Windows OS has no cat command run npm i jscat.

Save all and finally run:

npm run build && npm run package

The command generates custom-button-element.js that you can include in of an HTML page to see our custom element working.

Here is an example:

Summary

In summary we’ve:

  • Added important libraries for implementation
  • Registered the component in browser’s CustomElementRegistry
  • Combined the build artifacts to a single file

Complete source code can be found here.

Did you learn something new? If so please clap ? button below️ so more people can see this.