Search code examples
angularweb-component

How to use a Service into a web component


I'm trying to make an angular web component by following this guide: https://www.codementor.io/blog/angular-web-components-8e4n0r0zw7

It works but when I have to inject services into my component, nothing works anymore, if I write (private service: DataService) in the constructor I have a blank screen and no console errors.

import {Component, Injector, Input, OnInit} from '@angular/core';
import {DataService} from '../../_service/data.service';

@Component({
  selector: 'optix-calendar',
  templateUrl: './optix-calendar.component.html',
  styleUrls: ['./optix-calendar.component.scss']
})
export class OptixCalendarComponent implements OnInit {
  @Input() apiKey = null;

  token = null;

  formData = {name: '', email: ''};
  formSubmitted = false;

  constructor(private dataService: DataService) {}

  ngOnInit(): void {
  }

  onSubmit(): void {
    this.formSubmitted = true;
  }

and this is app.module:

import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {NgModule, Injector} from '@angular/core';
import {createCustomElement} from '@angular/elements';
import {OptixCalendarComponent} from './optix-calendar/optix-calendar.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule} from '@angular/material/button';
import {MatInputModule} from '@angular/material/input';
import {MatCardModule} from '@angular/material/card';
import {HttpClient} from '@angular/common/http';


@NgModule({
  declarations: [OptixCalendarComponent],
  imports: [BrowserModule, FormsModule, BrowserAnimationsModule, MatButtonModule, MatInputModule, MatCardModule

    ],
  providers: [],
  entryComponents: [OptixCalendarComponent]
})
export class AppModule {
  constructor(injector: Injector) {
    const el = createCustomElement(OptixCalendarComponent, {injector});
    customElements.define('optix-calendar', el);
  }

  ngDoBootstrap(): void {
  }
}

Can you point me in the right direction in order to use a Service in my web component?


Solution

  • constructor(injector: Injector) {}
    
     ngDoBootstrap(): void {
        const el = createCustomElement(OptixCalendarComponent, {injector});
        customElements.define('optix-calendar', el);
      }
    

    And remove the selector from your component:

    @Component({
     // selector: 'optix-calendar',
      templateUrl: './optix-calendar.component.html',
      styleUrls: ['./optix-calendar.component.scss']
    })
    

    I think you are exporting an angular application not a web component: you call optix-calendar instead of app-root.