Search code examples
angulartypescriptproduction-environment

Angular template: Disable div in production mode


I have several divs in my webapp that are used solely for debugging, and I would like to remove these in production mode.

In my templates, I'm trying to do something like this:

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

However, this fails when running ng serve --prod with the following error:

ERROR in src/app/foo/foo.component.html(18,6): : Property 'environment' does not exist on type 'Foo'

Is there any way to disable these in production mode without adding another field to each component?

I'm using Angular cli 1.7.4 and Angular 5.2.10


Solution

  • You could create a directive to only show your div elements if environment.production is false. Something like in this blitzstack example: 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);
        }
      }
    
    }