Using dependency injection with components and directives
In Chapter 5, Getting Started with Angular Components and Directives, when we developed our first Angular directive, we saw how we can take advantage of the DI mechanism to inject services into our UI-related building blocks (that is, directives and components).
Let's take a quick look at what we did earlier, but from a DI perspective:
// ch5/tooltip/app.ts // ... @Directive(...) export class Tooltip { @Input() saTooltip: string; constructor(private el: ElementRef, private overlay: Overlay) { this.overlay.attach(el.nativeElement); } // ... } @Component({ // ... providers: [Overlay] }) class App {}
Most of the code from the earlier implementation is omitted because it is not directly related to our current focus.
Note that the constructor of Tooltip
accepts two dependencies:
- An instance of the
ElementRef
class - An instance of the
Overlay
class
The types of dependencies are the tokens associated with their...