【问题标题】:How do I overwrite an existing component in angular?如何以角度覆盖现有组件?
【发布时间】:2018-11-15 03:41:03
【问题描述】:

我正在尝试用 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

感谢您的帮助。

【问题讨论】:

  • 您要解决什么问题?您使用“覆盖”和“模拟”之类的词,但随后显示与路由相关的代码。这是单元测试吗?
  • 我想在 app.module.ts 中插入几行代码,用 app-mock-of-original 组件覆盖 app-original 组件。我正在寻找类似的东西,但对于组件:{提供:OrginalComponent,useExisting:MockOfOrginalComponent},
  • 我不认为这可以使用提供者进行更改。提供者用于依赖注入。在运行时,Angular 会将组件添加到要注入的提供程序中,但是更改类关联不会改变模板在运行时选择要创建的组件的方式。请记住,组件具有“提供者”属性,可让您覆盖组件和视图的可注入项。也许这为您提供了一些其他选择。

标签: angular components angular5 selector


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢,这正是我想要的。我有一个带有两种类型按钮的角度库,一种是单选按钮,另一种是普通按钮。根据应用的不同,按钮布局应该有所不同。
  • 是否可以通过 SettingsService 变量动态控制组件的选择?
  • 只是想知道MockAppComponent 是否可以实现/扩展AppComponent 然后覆盖一些功能?
猜你喜欢
  • 1970-01-01
  • 2019-03-20
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
相关资源
最近更新 更多