如何覆盖 Angular 5 中的组件? [英] How to overwrite a component in Angular 5?

查看:23
本文介绍了如何覆盖 Angular 5 中的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Angular 5 中有一个 组件

I have a component <my-component> in Angular 5

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

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

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

And in my html I have something like this:

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

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

I need to overwrite click function to execute: console.log('Param: ' + param);

我该怎么做???

推荐答案

在你的 app.module.ts

In your 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

Your 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 中重定向

The trick is the redirection in your AppModule

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

我在本地进行了测试,它运行正常.如果它不试试这个

I tested this locally and it worked properly. If it doesn't try this

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

当您从(外部)模块导入两个组件时,这也适用.

This also works when you import both components from (external) modules.

这篇关于如何覆盖 Angular 5 中的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆