StaticInjectorError(AppModule)[NgForOf-> TemplateRef]

时间:2019-06-11 07:26:15

标签: javascript angular typescript angular7 angular-directive

我在Angular7中创建了一个Directive,但是当我需要使用它时,它会向我显示此错误:

  

错误:StaticInjectorError(AppModule)[NgForOf-> TemplateRef]:     StaticInjectorError(平台:核心)[NgForOf-> TemplateRef]:       NullInjectorError:没有TemplateRef的提供者!   错误:StaticInjectorError(AppModule)[NgForOf-> TemplateRef]:     StaticInjectorError(平台:核心)[NgForOf-> TemplateRef]:

我在SharedModule中创建此指令:

@NgModule({
  declarations: [FilderrorComponent, UploadfileComponent, ImageComponent, ValidatePermissionDirective],
  imports: [
    CommonModule
  ],
  exports: [ FilderrorComponent, UploadfileComponent, ImageComponent, ValidatePermissionDirective]
})
export class SharedModule {

    static forRoot(): ModuleWithProviders {
      return {
        ngModule: SharedModule,
        providers: [ FilderrorComponent, UploadfileComponent, ImageComponent , ValidatePermissionDirective]
      };
  }
}

这是我的指令:

@Directive({
  selector: '[appValidatePermission]'
})
export class ValidatePermissionDirective implements OnInit {

  show: boolean;
  constructor(private templateRef: TemplateRef<any>,
              private viewContainerRef: ViewContainerRef
    ,         private dynamic: DynamicPermissionService) { }

  // tslint:disable-next-line:no-input-rename
  @Input() AccessName: string;

  ngOnInit() {
    this.ValidatePemission();
    if (this.show) {
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainerRef.clear();
    }
  }
  ValidatePemission() {
    console.log('AccessName : ', this.AccessName);
    const find = this.dynamic.dynamicModel.find(x =>
      !! x.actionsVM.find(z => z.actionEnglishName === this.AccessName));
    console.log(find);
    if (find) {
        console.log(true);
        this.show = true;
      } else {
        console.log(false);
        this.show = false;
      }
  }
}

我在shareModule中定义了AdminModule :

@NgModule({
  declarations: [],
  imports: [
    SharedModule,
    AdminpanelRoutingModule,

  ],
  providers: [Toolkit, { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }]
})
export class AdminpanelModule { }

并且我在HTML中使用Directive

<span [appValidatePermission]="CreateRole">
  <router-outlet></router-outlet>
</span>

出了什么问题???我该如何解决?

1 个答案:

答案 0 :(得分:0)

我认为问题出在templateRef为null。 尝试初始化它,然后再使用它