Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 647
4e554c4c Avatar asked Dec 03 '22 19:12

4e554c4c


2 Answers

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);
    }
  }

}
like image 130
A.Winnen Avatar answered Jan 17 '23 22:01

A.Winnen


Your condition is right: *ngIf="!environment.production"

Though you need to import the environment object in your component.

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

Component({...})
export class MyComponent {
  public environment = environment;
}
like image 29
Ploppy Avatar answered Jan 17 '23 22:01

Ploppy