Home > Software design >  Angular 15 No provider for TemplateRef when structural directive used as hostDirective
Angular 15 No provider for TemplateRef when structural directive used as hostDirective

Time:01-28

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.

stackblitz to play

CodePudding user response:

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.

CodePudding user response:

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
  • Related