Assert That A Component Can Only Be Used As A Child Of Another Component
Suppose I have two components, and , and I want to assert at runtime that the Child component is used within the Parent component as follows:
Solution 1:
You can inject the host of the child component with the following syntax:
import { Component, Optional, Host, Inject, forwardRef } from'@angular/core';
import { ParentComponent } from'./parent.component';
...
exportclassChildComponent {
constructor(@Optional() @Host() @Inject(forwardRef(() => ParentComponent)) parent) {
console.log("Has valid parent:", !!parent);
}
}
See this stackblitz for a demo.
If you want Angular to throw an exception when the appropriate parent component is not found, remove the @Optional
decorator:
constructor(@Host() @Inject(forwardRef(() => ParentComponent)) parent) {
console.log("Has valid parent!");
}
See this stackblitz for a demo.
Post a Comment for "Assert That A Component Can Only Be Used As A Child Of Another Component"