简体   繁体   中英

How to use Angular Component in Angular Element?

I have static page where I imported my custom defined angular element

<html>
    <head>...</head>
    <body>
        <my-element></my-element>
        <script src="elements.js"></script> 
    </body>
</html>

app.module.ts

import { NgModule, Injector } from '@angular/core';  
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { createCustomElement } from '@angular/elements';
import { CalendarModule } from 'primeng/calendar';
import { MyElementComponent } from './my-element.component'; 

@NgModule({
    imports        : [
        BrowserModule,
        BrowserAnimationsModule, 
        CalendarModule
    ], 
    declarations   : [
        MyElementComponent
    ],
    entryComponents: [ 
        MyElementComponent  
    ] 
})

export class AppModule { 
    constructor(private injector: Injector) { };

    ngDoBootstrap() { 
        const customElement = createCustomElement(MyElementComponent, { injector: this.injector });

        customElements.define('my-element', customElement); 
    };
};

my-element.component.html

<!--some HTML-->
    <p-calendar [touchUI]="true" #calendar></p-calendar>
<!--some HTML-->

my-element.component.ts

import { Component, ViewChild } from '@angular/core'; 
import { Calendar } from 'primeng/calendar';

@Component({ 
    templateUrl  : './my-element.component.html',
    styleUrls    : ['./my-element.component.css'] 
})

export class MyElementComponent { 
    @ViewChild('calendar') calendar: Calendar;

    ngAfterViewInit() {
        console.log(this.calendar); // OUTPUT OK/CALENDAR INSTANTIATED
    };
};

So, I have 3rd party npm calendar angular component imported in angular element which is injected in static web page.

Calendar is rendered and instantiated, but it doesn't apply it's css, and therefore isn't working as expected.

For example this ui-calendar class, it is there but isn't applied

Where is the problem?

Try to play around with the ViewEncapsulation to None or Native depending on what you want.

Take a look at this response: https://stackoverflow.com/a/55735139/11448530

Using this for example:

platformBrowserDynamic().bootstrapModule(AppModule, [
  {
      defaultEncapsulation: ViewEncapsulation.Native 
  }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM