简体   繁体   中英

Disable component if environment angular is production

I have something like this

enviroment.ts

export const environment = {
  production: false
};

And in app.module.ts

I have something like this

@NgModule({
  declarations: [AppComponent, VersionComponent],
  imports: [],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule { }

The problem I have is that based on environment.production i need to declare or not to declare VersionComponent

Something like this

if (environment.production) {VersionComponent}

The problem is that if is not allowed declarations , has someone had similar problem?

Module metadata is consumed by the angular compiler, which only supports subset of JavaScript . Fortunately, that subset includes the conditional and spread operators, allowing us to write:

declarations: [
  AppComponent,
  ...(environment.production ? [VersionComponent] : []),
],

Or course, this may cause syntax errors if any templates make use of the undefined component ...

Alternatively, you could replace the component with a different definition that has the same selector, but doesn't do anything:

declarations: [
  AppComponent,
  environment.production ? VersionComponent : VersionComponentStub,
],
const declarations =  [AppComponent];
let extraDeclarations = [];
if(environment.production) {
    extraDeclarations = [VersionComponent]
}

const finalDeclarations = declarations.concat(extraDeclarations);
@NgModule({
    declarations: finalDeclarations
const _declarations = [AppComponent];

if( environment.production )
   _declarations.push( VersionComponent );

@NgModule({
  declarations: [
    _declarations
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

works for me ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM