角度模板:在生产模式下禁用div

问题描述 投票:0回答:2

我的webapp中有几个div ,仅用于调试,我想在生产模式下将其删除。

在我的模板中,我正在尝试执行以下操作:

<div *ngIf=!environment.production>{{ fooState | async | json}}</div>

但是,这在运行ng serve --prod时失败,并显示以下错误:

src / app / foo / foo.component.html(18,6)中的错误:类型'Foo'上不存在属性'environment'

有什么方法可以在生产模式下禁用这些功能,而无需在每个组件中添加另一个字段?

我正在使用Angular CLI 1.7.4和Angular 5.2.10

angular typescript production-environment
2个回答
3
投票

您的条件是正确的: *ngIf="!environment.production"

尽管您需要在组件中导入环境对象。

import { environment } from 'src/environments/environment';

Component({...})
export class MyComponent {
  public environment = environment;
}

2
投票

您可以创建一个指令,以仅在environment.production为false时显示div元素。 像这样的blitzstack示例中的内容: https ://stackblitz.com/edit/angular-eziobx

import { Directive, ViewContainerRef, OnInit, TemplateRef } from '@angular/core';
import { environment } from '../environment';

/**
 * usage: <div *hideProd></div>
 */
@Directive({
  selector: '[hideProd]'
})
export class HideProdDirective implements OnInit{

  constructor(private templateRef: TemplateRef<any>, private viewContainerRef: ViewContainerRef) { }

  ngOnInit(): void {
    if(!environment.prod){
      this.viewContainerRef.createEmbeddedView(this.templateRef);
    }
  }

}
© www.soinside.com 2019 - 2024. All rights reserved.