angular - 覆盖组件,比如服务?

标签 angular angular2-providers

假设我们导入了一个 Angular Material 模块:

 providers:[],
 imports : [MaterialInput]

MaterialInput 中,有一个名为:MaterialInputComponent 的组件

出于某些原因,我想用我自己的组件覆盖该组件

所以我想说:

 providers:[
    {
       provide: MaterialInputComponent,
       useClass : MyOwnInputComponent
    }
 ],
 imports : [MaterialInputModule]

我知道我们可以像那样覆盖服务,但它也可以用于组件或指令吗?

更新: 我不是在寻找组件继承,我想要的是使用类似 Material Module 的东西,但有时我想覆盖它的一些组件行为,就像你对服务所做的那样。

喜欢:

如果这是 MaterialInput 组件背后的原始代码,它在我的节点模块中。

  @Component({})
  export class OriginalMaterialInputComonent{
        greet(){ alert('Say Aloo'); }
  }

我有一个类似的类:

  @Component({})
  export class OverrideMaterialInputComonent{

        greet(){ alert('Say yes we can'); } // overriden function
  }

并且,假设我正在导入孔 MaterialInputModule

declarations:[
   {
    provide: OriginalMaterialInputComonent,
    useClass : OverrideMaterialInputComonent
  }
],
  imports : [MaterialInputModule]

这可行吗?

最佳答案

你可以为此使用装饰器,你可以查看下面的 jsfiddle 示例

Overriding components

https://jsfiddle.net/mohan_rathour/sqv0jx21/

关于angular - 覆盖组件,比如服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176470/

相关文章:

Angular:使用服务延迟加载模块

javascript - 这 3 个 Angular2 命令导入什么?

unit-testing - 带有模拟的 Angular 2 TestBed

Angular Material : Mat Table sometimes get updated in real-time sometimes not

angular - 如何从ngrx store获取值

javascript - 创建自定义变量时出错

angular - 如何将 yarn 设置为 Angular CLI 的默认 packageManager?我得到 "Cannot read property ' 值为 null”

angular - 在工作区中运行 Angular CLI 时,此命令不可用

Angular2,AoT编译: Cannot determine the module for component AppComponent