I have an abstract component AbstractPageComponent (an abstract class describing a component), the template of an instance of which can contain an instance of another abstract component. Specifically, an instance of AbstractPageComponent will contain a component with a list of entities (people, for example). The component with the list of entities is itself an instance of another abstract component, AbstractListComponent. I want to access this child component with a @ViewChild() decorator. However, simply writing @ViewChild(AbstractListComponent) doesn't work. So, right now I have to manually declare the ViewChild properties for each instance of AbstractPageComponent:
// task page component
@ViewChild(TaskListComponent) private readonly listComponent!: TaskListComponent;
// employee page component
@ViewChild(EmployeeListComponent) private readonly listComponent!: EmployeeListComponent;
This seems really excessive. I was wondering if there's a way to "provide" a different component to each instance of AbstractPageComponent, similar to a service? Something like:
import { AbstractListComponent } from '...';
@Component({
template: ''
})
export abstract class AbstractPageComponent {
@ViewChild(AbstractListComponent) public readonly listComponent!: AbstractListComponent;
...
}
import { TaskListComponent } from '...';
import { AbstractListComponent } from '...';
// TaskListComponent extends AbstractListComponent
@Component({
...
providers: [
{
provide: AbstractListComponent,
useClass: TaskListComponent
}
]
})
export class TaskPageComponent extends AbstractPageComponent { ... }
yes, it is possible. Just use
useExistingfor the provider piece. Just remember that there providers would be available in the components subtree only.in this example existing instance of TaskListComponent would be injected when something would try to inject AbstractListComopnent
@Injectable()withoutprovideIn: 'root'rather tells angular to precompile the service, so it's constructor would inject some services that you are injecting there. You can provide random class somewhere and then use it as a service even without Injectable annotation if it has no dependencies (there is however no reasons to do it)