angular - 如何以 Angular 覆盖现有组件?

标签 angular components angular5 selector

我正在尝试以 Angular 覆盖现有组件。

我的原始组件是:

@Component({
  selector: 'app-orginal',
  templateUrl: './orginal.component.html',
  styleUrls: ['./orginal.component.css']
})
export class OrginalComponent implements OnInit {
}

在 app.component.html 中,我使用了这样的原始组件:

<app-orginal></app-orginal>

您想做的是用模拟组件覆盖原始组件。

这是我的模拟组件:

@Component({
  selector: 'app-mock-of-orginal',
  templateUrl: './mock-of-orginal.component.html',
  styleUrls: ['./mock-of-orginal.component.css']
})
export class MockOfOrginalComponent implements OnInit {
}

与此答案相关https://stackoverflow.com/a/49327712/7717382我尝试在我的 app.module.ts 中使用这个解决方案:

@NgModule({
    declarations: [
        AppComponent,
        OrginalComponent,
        MockOfOrginalComponent
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        RouterModule.forRoot([
            {path: 'app-mock-of-orginal', component: MockOfOrginalComponent},
            {path: 'app-orginal', redirectTo: 'app-mock-of-orginal', pathMatch: 'full'},
        ]),
    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {
}

但它不起作用。我做错了什么?

这是我的 git-hub 项目:https://github.com/annalen/overwrite-component

感谢您的帮助。

最佳答案

要用替代品替换组件,它必须替换原始声明。您的示例是同时声明两个组件,但使用不同的选择器。关键是使用相同的选择器,但只声明一个。

@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 不允许您声明两个共享同一选择器的组件,但如果您不想更改模板,则必须使用该选择器。

我不确定你为什么要这样做。也许这不是您想要的。

关于angular - 如何以 Angular 覆盖现有组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50703697/

相关文章:

javascript - 嵌套的 Angular 响应式表单和组件重用

html - 未捕获的 ReferenceError : Cannot access 'MaterialModule' before initialization

cakePHP 分页器未传递 passargs

.net - .NET 的停靠面板组件允许停靠在标签页内?

angular - Angular 如何处理 Angular 库中的非导入模块?

angular - 使用 Bootstrap 和 sass 对 Angular 应用程序和库进行主题化

javascript - 在 create-react-library 库中配置相对于根目录的导入

javascript - Angular 通用获取错误 : You must pass in a NgModule or NgModuleFactory to be bootstrapped

javascript - Angular 5 http post方法在nodejs中未调用

在多个选项卡中打开时 Angular 5 应用程序卡住 - chrome