【问题标题】:How to overwrite a component in Angular 5?如何覆盖 Angular 5 中的组件?
【发布时间】:2018-08-25 17:11:18
【问题描述】:

我在 Angular 5 中有一个组件 <my-component>

@Component({
selector: 'my-component',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class MyComponent {

click(param: string){
 console.log(param);
}

在我的 html 中有这样的内容:

<my-component (click)="click('Hello world')"></my-component>

我需要覆盖点击函数来执行: console.log('Param: ' + param);

我该怎么做???

【问题讨论】:

  • 你可以访问源代码吗?
  • 不,我不知道。我的组件对我来说是 npm 包
  • 那扩展组件怎么样?然后你会使用&lt;my-extended-component ...&gt;
  • 我需要用相同的选择器覆盖现有的选择器

标签: angular components angular5


【解决方案1】:

在您的 app.module.ts 中

import { OriginalComponent } from './original/original.component';
import { MockOfOriginalComponent } from './mock/mock-of-original.component';

@NgModule({
  declarations: [
    AppComponent,
    WelcomeComponent,
    OriginalComponent,
    MockOfOriginalComponent

  ],
  providers: [],
  imports: [
    BrowserModule,
    HttpClientModule,
    RouterModule.forRoot([
      { path: 'welcome', component: WelcomeComponent },
      { path: 'pm-mock-of-original', component: MockOfOriginalComponent },
      { path: 'pm-original', redirectTo: 'pm-mock-of-original' },
    ]),
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

您的原始组件

@Component({
    moduleId: module.id,
    selector: 'pm-original',
    templateUrl: 'original.component.html',
    styleUrls: ['original.component.scss']
    })

    export class OriginalComponent {

    }

你的 MockOfOriginalComponent

@Component({
    moduleId: module.id,
    selector: 'pm-mock-of-original',
    templateUrl: 'mock-of-original.component.html',
    styleUrls: ['mock-of-original.component.scss']
    })

    export class MockOfOriginalComponent {

    }

诀窍在于您的 AppModule 中的重定向

  { path: 'pm-mock-of-original', component: MockOfOriginalComponent },
  { path: 'pm-original', redirectTo: 'pm-mock-of-original' }

我在本地对此进行了测试,它工作正常。如果它不尝试这个

  { path: 'pm-mock-of-original', component: MockOfOriginalComponent },
  { path: 'pm-original', redirectTo: 'pm-mock-of-original', pathMatch: 'full' }

当您从(外部)模块导入两个组件时,这也有效。

【讨论】:

  • @Matteo Calò:如果这对您有帮助,我希望您将此答案标记为您的问题的解决方案。提前非常感谢。
  • 我在控制台中遇到问题:模块“AppModule”声明的意外值“[object Object]”
  • 请提供您的 AppModule,以便我检查问题所在。
  • @Matteo Calò:看来我犯了一个错误。显然组件不能以这种方式被覆盖。仅在测试框架中。这仅适用于服务的东西。但我有另一个解决方案。我在上面调整了答案。
  • 这是一个非常有趣的解决方案,但是我从依赖项中继承了 OriginalComponent。那么,使用您的解决方案,我需要扩展继承的 routingModule,我该怎么做?
猜你喜欢
  • 1970-01-01
  • 2017-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多