Search⌘ K

Angular Dependency Injection and Child Components

Explore Angular's dependency injection system to provide services to components and manage child components. Understand how to use @ViewChild to control elements like MatSidenav and handle domain events to create interactive UI features.

We'll cover the following...

Angular uses a technique known as Dependency Injection (DI) to provide services to components. This means that a class can request an instance of a service that it depends on, and Angular will resolve this dependency at runtime. DI in Angular works through the constructor function of a component:

TypeScript 4.9.5
export class UserDetailsComponent implements OnInit {
loggedInUserName: string = 'logged_in_user';
constructor(private broadcastService: BroadcastService) {
}
ngOnInit(): void {
}
@Output() notify = new EventEmitter();
onLoginClicked() {
console.log(`UserDetailsComponent : onLoginClicked()`);
this.notify.emit('UserDetailsComponent : emit value');
this.broadcastService.broadcast(
EventKeys.LOGIN_BUTTON_CLICKED,
'UserDetailsComponent: LOGIN_BUTTON_CLICKED'
);
}
}

Here, we have updated the UserDetailsComponent class in two areas:

  • Firstly, we have added a private member variable through our constructor function named broadcastService, of type BroadcastService on lines 5. By adding this private member variable into the constructor and specifying its type, the Angular DI process will take over when creating this class and pass the instance of the BroadcastService into this component as an argument.

  • The second change we have made to this class is to call the broadcast function on our local instance of the BroadcastService on lines 16–19 and send an EventKeys.LOGIN_BUTTON_CLICKED event to the event bus.

Note: We have included a string ...