【问题标题】:Passing to a method a inheriting-component as a parameter using its base-class使用其基类将继承组件作为参数传递给方法
【发布时间】:2019-12-16 19:01:09
【问题描述】:

(我正在构建一个接受继承组件并显示它们的模态系统)

我正在尝试将继承组件传递给使用其基类作为类型的方法。

@Component(...) export class BaseCompComponent implements OnInit

@Component(...) export class ActualComponent extends BaseCompComponent {
  method(b:BaseCompComponent) { }

  Calling it like so: method(ActualComponent) --> ERROR

错误:

“typeof ActualComponent”类型的参数不能分配给“BaseCompComponent”类型的参数。 “typeof ActualComponent”类型中缺少属性“ngOnInit”,但在“BaseCompComponent”类型中是必需的。

基类实现了这个,我做错了什么?这似乎相当简单的 OOP ?

(如果问题不清楚,我还在stackblitz上写了一个示例

参见“Hello”组件第 19 行)

谢谢!

【问题讨论】:

    标签: angular oop inheritance


    【解决方案1】:

    您需要指定ActualComponent 是类型而不是对象。

    import { Component, Input, Type } from '@angular/core';
    import { BaseCompComponent } from './base-comp/base-comp.component'
    import { ActualComponent } from './actual/actual.component'
    
    @Component({
      selector: 'hello',
      template: `<h1>Hello {{name}}!</h1>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent  {
    
      @Input() name: string;
    
      method(b: Type<BaseCompComponent>) { 
    
      }
      constructor () { 
        this.method(ActualComponent);
      }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2018-12-11
      • 2020-07-29
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      相关资源
      最近更新 更多