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

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

问题描述

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

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>

我需要覆盖click函数才能执行: 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 { }

您的OriginalComponent

Your OriginalComponent

@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天全站免登陆