gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 18:37:52 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com