How do I overwrite an existing component in angular?

北城以北 提交于 2019-12-06 01:19:04

To replace a component with an alternative it has to replace the declaration of the original. You're example is declaring both components at the same time, but with different selectors. The key is to use the same selector, but only declare one.

@Component({selector: 'app-original'})
export class MockAppComponent {
      // this will replace AppComponent
}

@Component({selector: 'app-original'})
export class AppComponent {
}

// You could use a value from environment.ts
// if you need to toggle this at compile time.
const mockFlag = true;

@NgModule({
    declarations: [
       mockFlag ? MockAppComponent : AppComponent,
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot([]),
    ],
    providers: [],
    bootstrap: [mockFlag ? MockAppComponent : AppComponent]
})
export class AppModule {
}

Angular will not allow you to declare two components that share the same selector, but you have to use that selector if you don't want to change your templates.

I'm not sure why you want to do this. Maybe this isn't want you need.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!