Sub topic 15
Injecting a parent component through an abstract token
This chapter assumes you know how inject() and providers work, and that you have read the earlier chapters on element injectors and resolution modifiers. It combines those ideas into one pattern. A child component or directive talks to its parent through a small abstract contract, so the child never imports the concrete parent class.
The problem the pattern solves
A dialog contains a close button, and the button must tell the dialog to close. The obvious approach is inject(DialogComponent) inside the button component. This works, but it has three costs:
- The button file imports the dialog file. If the dialog's file also imports the button, you get a circular import.
- The button only works inside that one dialog class. A drawer or popover that wants the same button cannot use it.
- Tests must build a real dialog just to check that a button calls
close().
The fix is to inject an abstraction. The parent publishes itself under an abstract token, and the child asks for the token.
The token is an abstract class
A TypeScript interface is erased at compile time, so it cannot be used as an injection token. An abstract class exists at runtime and also describes a type, so it can serve as both the token and the contract:
export abstract class Panel {
abstract close(): void;
}You could also use new InjectionToken<PanelApi>('Panel') with a separate interface. The abstract class needs less code and gives the child a typed value without a second declaration. The cost is that Panel is now a real class that ships in the bundle, though it is tiny.
Registering the parent under the token
The parent extends the abstract class and lists a provider for it:
import { Component, forwardRef } from '@angular/core';
import { Panel } from './panel';
@Component({
selector: 'app-dialog',
standalone: true,
providers: [{ provide: Panel, useExisting: forwardRef(() => DialogComponent) }],
template: `<ng-content />`,
})
export class DialogComponent extends Panel {
close(): void {
// hide the dialog
}
}Three details matter here:
provide: Panelis the token that children will request.useExistingis an alias. It tells Angular to resolvePanelby looking upDialogComponentin the same injector. Angular already created that instance when it created the component, so the alias returns the live parent.forwardRef(() => DialogComponent)is needed because the decorator runs before the class binding is initialized. The arrow function delays the read until Angular needs the value.
Requesting the parent from a child
import { Component, inject } from '@angular/core';
import { Panel } from './panel';
@Component({
selector: 'app-dialog-close',
standalone: true,
template: `<button (click)="panel?.close()">Close</button>`,
})
export class DialogCloseComponent {
protected readonly panel = inject(Panel, { optional: true });
}The child imports only Panel. Used in a template, it looks like this:
import { Component } from '@angular/core';
import { DialogComponent } from './dialog.component';
import { DialogCloseComponent } from './dialog-close.component';
@Component({
selector: 'app-confirm',
standalone: true,
imports: [DialogComponent, DialogCloseComponent],
template: `
<app-dialog>
<p>Discard unsaved changes?</p>
<app-dialog-close />
</app-dialog>
`,
})
export class ConfirmComponent {}Why the lookup succeeds
The close button is projected content. In ConfirmComponent's template, <app-dialog-close> is a DOM child of <app-dialog>. Element injectors follow that declaration structure, so the button's parent injector is the one on the <app-dialog> element, and that injector holds the Panel provider.
The resolution order is the one from the earlier chapter. Angular checks the requesting element's own injector first, then each ancestor element injector, and only then the environment injectors. If nothing provides Panel, the lookup fails. With optional: true, it returns null instead of throwing.
Choosing the options
| Option | Effect on this pattern |
|---|---|
| `optional: true` | The child works outside any panel, and `panel` is `null`. Without it, such a child throws `NullInjectorError`. |
| `self: true` | Looks only on the child's own element. A directive that is placed on the same element as the parent could use this. A child element would not find the parent. |
| `skipSelf: true` | Starts at the parent injector. A component that is also a `Panel` uses this to find the next enclosing panel. |
| `host: true` | Stops the search at the host element of the current component's view. See the warning below. |
Nested panels with skipSelf
The nearest Panel wins. A close button inside an inner dialog closes the inner dialog, which is usually what you want. A dialog may also need to find the dialog that encloses it. Because the dialog provides Panel itself, a plain inject(Panel) would return itself, so it must skip its own injector:
import { Component, forwardRef, inject } from '@angular/core';
import { Panel } from './panel';
@Component({
selector: 'app-nested-dialog',
standalone: true,
providers: [{ provide: Panel, useExisting: forwardRef(() => NestedDialogComponent) }],
template: `<ng-content />`,
})
export class NestedDialogComponent extends Panel {
private readonly outer = inject(Panel, { skipSelf: true, optional: true });
close(): void {
// hide this dialog, then optionally close the outer one
this.outer?.close();
}
}Pitfalls
- Using
viewProvidersinstead ofproviders. AviewProvidersentry is visible only to the component's own template, not to projected content. InConfirmComponentabove, the close button is projected content, so it would not findPanel. Useproviderswhen projected children must see the parent. UseviewProvidersonly when you want to hide the token from projected content. - Forgetting
optional. Without it, placing<app-dialog-close>outside a dialog throwsNullInjectorError: No provider for Panel. Decide deliberately whether the child may stand alone. If it must not, leaveoptionaloff, so the error tells you about the misuse. - Expecting
host: trueto cross the content boundary.hostlimits the search to the host element of the current view. It is useful for hiding parents from a directive in a component's template. Do not add it to a projected child, because it can stop the search before it reaches the parent. - Putting
PanelinprovidedIn: 'root'by accident. If an environment injector also providesPanel, the element injector wins whenever a parent exists. The root provider silently becomes the fallback for stray children. Make sure that is what you want. - Skipping the
extends.useExistinghands the child aDialogComponent. If the class does not extend or implementPanel, TypeScript will not warn you, because the provider object is not type-checked against the token. Writeextends Panel(orimplements Panel) so the compiler enforces the contract.
Testing the child alone
Because the child depends only on Panel, you can test it with a stub supplied at module level. The close button declares no providers of its own, so the TestBed providers apply:
import { TestBed } from '@angular/core/testing';
import { DialogCloseComponent } from './dialog-close.component';
import { Panel } from './panel';
it('asks the panel to close when clicked', () => {
let closeCalls = 0;
TestBed.configureTestingModule({
imports: [DialogCloseComponent],
providers: [{ provide: Panel, useValue: { close: () => { closeCalls++; } } }],
});
const fixture = TestBed.createComponent(DialogCloseComponent);
fixture.detectChanges();
fixture.nativeElement.querySelector('button').click();
expect(closeCalls).toBe(1);
});The parent is different. If you need to replace providers that a component declares for itself, use TestBed.overrideComponent, as in the chapter on testing scoped providers.
Summary of the pattern
- Define an abstract class that lists only what children need.
- Make the parent extend it and provide
{ provide: Token, useExisting: forwardRef(() => Parent) }inproviders. - In the child, call
inject(Token, { optional: true })or withoutoptionalwhen a parent is mandatory. - Add
skipSelfwhen a parent needs its own enclosing panel.
Exercise
A teammate changes DialogComponent to use viewProviders: [{ provide: Panel, useExisting: forwardRef(() => DialogComponent) }]. The <app-dialog-close> element is written between <app-dialog> and </app-dialog> in ConfirmComponent's template. What does the close button's panel field contain, and why?
Show answer
It is null because the button uses optional: true. Without optional, it would throw NullInjectorError. viewProviders entries are visible only to the dialog's own template, and the button is projected content declared in ConfirmComponent's template, so the lookup cannot see them. Switching back to providers fixes it.
Exercise
Why does the dialog register the alias with useExisting and not useClass: DialogComponent?
Show answer
useExisting makes Panel resolve to the DialogComponent instance that Angular already created for that element. useClass would construct a new DialogComponent object outside the view, so close() would act on an instance that is not displayed.
Exercise
A NestedDialogComponent calls inject(Panel, { optional: true }) without skipSelf to find its outer dialog. What does it get, and what is the fix?
Show answer
It gets itself, because it provides Panel on its own element and the lookup starts at the requesting element's injector. Add skipSelf: true so the search starts at the parent injector.