微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使自定义指令在共享组件中生效?

如何解决如何使自定义指令在共享组件中生效?

在我的 Angular 9 应用程序中,我编写了一个自定义指令,src/directives/is_mobile.directive.ts,如下所示......

import { Directive,OnInit,TemplateRef,ViewContainerRef } from '@angular/core';
import { DeviceDetectorService } from 'ngx-device-detector';
  
@Directive({
  selector: '[isMobile]'
})
export class IsMobileDirective implements OnInit {

  constructor(private deviceService: DeviceDetectorService,private templateRef: TemplateRef<any>,private viewContainer: ViewContainerRef) { }

  ngOnInit() {
    if (this.deviceService.isMobile()) {
      console.log("a mobile device!");
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      console.log("not a mobile device!");
      this.viewContainer.clear();
    }
  }
}

我想在共享组件中使用它。我的共享模块看起来像这样......

@NgModule({
    declarations: [
      ArticleComponent,IsMobileDirective,],imports: [
      MatTableModule,CommonModule,browserAnimationsModule,MomentModule,exports: [
      ArticleComponent,entryComponents: [
    ],})
export class SharedModule { }

但是当我在共享组件模板中执行此操作时...

<mat-table *!isMobile #table [dataSource]="dataSource">
...
</mat-table>

在非移动平台上,内容不会出现。同样,如果我做相反的事情,什么也不会出现

<mat-table *isMobile #table [dataSource]="dataSource">
...
</mat-table>

如果我完全删除属性,表格就会出现,但现在我已经违背了编写指令的目的......

<mat-table #table [dataSource]="dataSource">
...
</mat-table>

如何让我的指令生效?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。