Skip to content

Conversation

@SkyZeroZx
Copy link
Contributor

Add section about assertInInjectionContext

@SkyZeroZx SkyZeroZx force-pushed the docs/add-assert-injection branch from 519ab59 to 135fcfa Compare December 7, 2025 04:45
@martinboue
Copy link
Owner

@SkyZeroZx Thank you for your contribution!

I've personally never used assertInInjectionContext before. Besides resolvers or guards, I never use helpers functions that need injection context. That said, I can see the value, especially for library authors.

To make sure this tip is broadly useful and not too niche or advanced (I try to keep Angular Tips accessible), could you please provide a real-world example of a helper function that would benefit from this? Thanks!

@martinboue martinboue added documentation Improvements or additions to documentation enhancement New feature or request labels Dec 9, 2025
@SkyZeroZx
Copy link
Contributor Author

The most common case, if you have several components or logic that need to access the DOM, is that instead of injecting ElementRef and then NativeElement, it's more practical to have a helper for that, and as you point out, for libraries it's an optimized way.

import { ElementRef, assertInInjectionContext, inject } from '@angular/core';
export function injectNativeElement<T extends Element>(): T {
    assertInInjectionContext(injectNativeElement);
    return inject(ElementRef).nativeElement;
}

Copy link
Owner

@martinboue martinboue left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A few minor comments, but nothing major. Thank you for your contribution ❤️

@SkyZeroZx SkyZeroZx force-pushed the docs/add-assert-injection branch from 135fcfa to 8519cb7 Compare December 11, 2025 18:57
@SkyZeroZx SkyZeroZx force-pushed the docs/add-assert-injection branch from 8519cb7 to 6391c63 Compare December 12, 2025 18:04
@martinboue
Copy link
Owner

I took the liberty of changing the order of the two tips and adding the version number to the links to angular.dev, I hope you don't mind.

Thanks again and congrats for being the first PR contributor of Angular Tips! 🎉

@martinboue martinboue merged commit 71a47e5 into martinboue:main Dec 19, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants