Member-only story
Angular — Using component-level scoped service to communicate between parent and children
Service is one of the fundamental concepts of Angular for managing shared state and logic. Do you know service can be in component-level? It is very useful for implementing component with dynamic child components, for example:
<google-map [key]="apiKey">
<google-map-marker *ngFor="let marker of markers"
[lat]="marker.lat"
[lng]="marker.lng">
</google-map-marker>
</google-map>
The <google-map>
is the parent component, which initializes and renders the Google map. The <google-map-marker>
is the child component that can be dynamically added to create markers on the map. Here is a guide about how you can use component-level service to implement this kind of components.
How to create a component-level service?
There isn’t actually much difference comparing with traditional global service. Just simply provide the injectable in your component rather than in your module:
import { Component } from '@angular/core';
import { GoogleMapService } from './google-map-service';@Component({
selector: 'google-map',
providers: [ GoogleMapService ],
template: ''
})
export class GoogleMapComponent {
constructor(
private googleMapService…