问题描述
在我的 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 (将#修改为@)