Angular: pass service from custom element to child custom element

480 views Asked by At

I have build a demo which creates 2 custom angular elements (checkout app.module). Works like a charm, but there is one problem, if I provide a service in the parent element (called BarComponent), it is not received by the its child CE (called TestComponent)

@Component({
  templateUrl: './bar-ce.component.html',
  providers: [TestService] // <-- this one!!
})
export class BarComponent {}

Inside its html it renders the child CE: TEST-CE: <test-ce></test-ce>

If I try to inject my TestService this way I get the "NullInjectorError: No provider for TestService!"

But if I provide it inside the app.module it all works again. So my question is, is there a way to fix this or is this just the way it is with CE (hope not)?

2

There are 2 answers

1
user14438281 On

Shared service should be provided in module. And latar initialize in constructor (private testService: Testservice)

0
JackyShows On

You should fix your problem doing like this according to your demo.

TEST-CE: <test-ce [testService]="testService"></test-ce>

And then on your child component doing like this.

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

import { TestService } from '../test.service';

@Component({
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  @Input() testService: TestService

  numInput: number;

  constructor() { 
    console.log('test-ce constructor.');
  }

  ngOnInit() {
    this.numInput = this.testService.value;
  }

}