Skip to content

Commit 9b494c7

Browse files
SkyZeroZxthePunderWoman
authored andcommitted
docs: Add DestroyRef.destroyed and usage in lifecycle guide (#64422)
PR Close #64422
1 parent ed99bc9 commit 9b494c7

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

adev/src/content/guide/components/lifecycle.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,12 @@ destroyed.
161161
You can also use `DestroyRef` to keep setup code close to cleanup code, rather than putting
162162
all cleanup code in the `ngOnDestroy` method.
163163

164+
##### Detecting instance destruction
165+
166+
`DestroyRef` provides a `destroyed` property that allows checking whether a given instance has already been destroyed. This is useful for avoiding operations on destroyed components, especially when dealing with delayed or asynchronous logic.
167+
168+
By checking `destroyRef.destroyed`, you can prevent executing code after the instance has been cleaned up, avoiding potential errors such as `NG0911: View has already been destroyed.`.
169+
164170
### ngDoCheck
165171

166172
The `ngDoCheck` method runs before every time Angular checks a component's template for changes.
@@ -237,7 +243,7 @@ See [Using DOM APIs](guide/components/dom-apis) for guidance on working with the
237243

238244
Render callbacks do not run during server-side rendering or during build-time pre-rendering.
239245

240-
#### after*Render phases
246+
#### after\*Render phases
241247

242248
When using `afterEveryRender` or `afterNextRender`, you can optionally split the work into phases. The
243249
phase gives you control over the sequencing of DOM operations, letting you sequence _write_

packages/core/src/linker/destroy_ref.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ const EXECUTE_CALLBACK_IF_ALREADY_DESTROYED = false;
2020
* is injected in a component or directive, the callbacks run when that component or
2121
* directive is destroyed. Otherwise the callbacks run when a corresponding injector is destroyed.
2222
*
23+
* @see [Lifecycle DestroyRef](guide/components/lifecycle#destroyref)
24+
*
2325
* @publicApi
2426
*/
2527
export abstract class DestroyRef {
@@ -43,11 +45,17 @@ export abstract class DestroyRef {
4345
* // stop the destroy callback from executing if needed
4446
* unregisterFn();
4547
* ```
48+
*
49+
* @see [Lifecycle DestroyRef](guide/components/lifecycle#destroyref)
50+
*
4651
*/
4752
abstract onDestroy(callback: () => void): () => void;
4853

4954
/**
5055
* Indicates whether the instance has already been destroyed.
56+
*
57+
* @see [Detecting instance destruction](guide/components/lifecycle#detecting-instance-destruction)
58+
*
5159
*/
5260
abstract get destroyed(): boolean;
5361

0 commit comments

Comments
 (0)