There is a possibility to bind standalone directives to component and directive decorator since angular version 15. Is there a way how to use structural directive (injecting templateRef) as hostDirective? It would be super usefull, but as I try anyhow I always get No provider for TemplateRef.
Asked
Active
Viewed 470 times
2 Answers
0
In your provided demo, you are using a standalone
directive into a no-standalone component, in this case HelloComponent
is contained in AppModule
, so in order to use your directive
, you would need to import into the imports
array, like if it were a module
@NgModule({
imports: [BrowserModule, FormsModule, MyIfDirective], // directive here
declarations: [AppComponent, HelloComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
If HelloComponent
were standalone
, then you would require to import it into the component's metadata imports
array.

Andres2142
- 2,622
- 2
- 14
- 19
-
1I've made HelloComponent standalone and it does not help... Could you please provide some working example? I've also tried to add @Injectable decorator to directive, but nothing helps. I would say it is not possible to use structural directives in hostDirectives – Eduard Void Jan 30 '23 at 07:53
-
1I am sorry, but your directive is not even applied in this case. Therefor it can't be used to hide/show content based on some input. Content will be shown all the time. My example is just a proof of failure :) but I would like to use structural directives as hostDirectives exactly and this is simulating it – Eduard Void Jan 30 '23 at 15:19
-1
you need make changes in directive.ts, don't declare TemplateRef in constructor rather declare it in directive class:
import {
Directive,
Injectable,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
@Injectable({
providedIn: 'root',
})
@Directive({
selector: '[myIf]',
standalone: true,
})
export class MyIfDirective {
tpl: TemplateRef<any>
constructor( private vcr: ViewContainerRef) {}
ngOnInit() {
this.vcr.createEmbeddedView(this.tpl);
}
}
you can refer to this stackblitz link, I have made changes in directive.ts: https://stackblitz.com/edit/angular-ivy-host-directive-uw5wkq

Muhammad Athaullah
- 25
- 3
-
your directive is nor working at all. as you won't inject TemplateRef, the content is still present in DOM. this.tpl is undefined in your ngOnInit – Eduard Void Jan 30 '23 at 07:48
-
Please check the stackblitz link that I have provided, working fine in it. – Muhammad Athaullah Jan 30 '23 at 08:52
-