Creating web component / element in Angular does not work

Discussão em 'Angular' iniciado por d00d, Dezembro 9, 2024.

  1. d00d

    d00d Guest

    I'm currently trying to create an Angular custom element / web component and integrate the web component in my ZK application. To start with an easy example, I just created a simple component that outputs a line of text.

    zk.component.ts

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

    @Component({
    selector: 'app-zk',
    imports: [],
    templateUrl: './zk.component.html',
    styleUrl: './zk.component.css'
    })
    export class ZkComponent implements OnInit {
    title: string = 'Angular19';
    ngOnInit() {
    }
    }


    zk.component.html:

    <label>Hi, this is my first {{ title }} component to import into ZK</label>


    The app.module.ts:

    import { NgModule, Injector } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { createCustomElement } from '@angular/elements';
    import { ZkComponent} from './zk/zk/zk.component';

    @NgModule({
    imports: [
    BrowserModule,
    ZkComponent
    ],

    providers: [],
    bootstrap: [],
    })
    export class AppModule {
    constructor(private injector: Injector) {
    const zkTestElement = createCustomElement(ZkComponent, { injector });
    customElements.define('zk-test', zkTestElement);
    }

    ngDoBootstrap() {}
    }


    I create the bundle via ng build --configuration production --output-hashing=none and a polyfills.js and main.js is created along with a index.html that loads both files:

    <!doctype html>
    <html lang="en" data-beasties-container>
    <head>
    <meta charset="utf-8">
    <title>Angular19</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
    <link rel="stylesheet" href="styles.css"></head>
    <body>
    <zk-test></zk-test>
    <script src="polyfills.js" type="module"></script><script src="main.js" type="module"></script></body>
    </html>


    When I access the index.html in a browser, I get this error in the console:

    main.js:7 SyntaxError: Failed to execute 'define' on 'CustomElementRegistry': "zktest" is not a valid custom element name
    at Mt.n.<computed> [as define] (polyfills.js:2:4356)
    at new e (main.js:7:108982)
    at Object.ɵfac [as useFactory] (main.js:7:109054)
    at Object.r [as factory] (main.js:7:5078)
    at Rt.hydrate (main.js:7:4221)
    at Rt.get (main.js:7:3406)
    at sl (main.js:4:2392)
    at S (main.js:4:2468)
    at useValue (main.js:7:1609)
    at Rt.resolveInjectorInitializers (main.js:7:3781)


    Any idea where I could have gone the wrong way?

    Continue reading...

Compartilhe esta Página