【问题标题】:Type checking components类型检查组件
【发布时间】:2017-11-10 16:12:23
【问题描述】:

我想将一个组件类作为输入传递给另一个组件:

@Component({selector: 'dummy-comp', template:'i am dummy'});
class Dummy {}

@Component({
  selector: 'not-so-dummy',
  template:'<ng-content *ngComponentOutlet="transcluded"></ng-content>'
})
class LessDummy {
  @Input() transcluded: ???
}

我应该使用什么类型的嵌入? Dummy 不扩展任何东西,而是使用 @Component 装饰器。另一方面,是一种 Component 类型,它从 Directive 扩展...这里是一些附加测试:

let dummy = Dummy, component = Component;
typeof dummy // "function"
dummy.name // "Dummy"
typeof component // "function"
component.name // "DecoratorFactory"
dummy instanceof component // false

如果我理解正确,我可以使用Function 作为transcluded 输入的类型,但理想情况下我想缩小范围。也许我以错误的方式解决这个问题,但这是我想要实现的目标:

<div [ngSwitch]="getTypeOf(input)">
  <div *ngSwitchCase="'Component?'">
    <ng-content *ngComponentOutlet="input"></ng-content>
  </div>
  <span *ngSwitchCase="'string'">{{input}}</span>
  <span *ngSwitchCase="'function'">{{input()}}</span>
</div>

我完全不知道将它放在我的 getTypeOf 函数中的逻辑是什么。

编辑: 根据this website

原始构造函数的原型被复制到 f 的原型中,以确保我们创建 Person 的新实例时 instanceof 运算符按预期工作。

这可以解释为什么instanceof 不起作用。

edit2Reflect 祝你好运:

 Reflect.getMetadata('annotations',dummy)[0].selector // "dummy-comp"

【问题讨论】:

  • instanceof 你在找什么? MDNinstanceof
  • 你能用一个函数来测试所有的可能性吗?所以你传入组件和if(input instanceof comp1)等等。然后返回一个字符串在前端开启?
  • 在这种情况下我不是传递一个实例而是一个类,所以类的类型应该是函数
  • 一旦你在浏览器中,所有的打字稿输入都会消失,除非你能想出一些可靠的方法来鸭式输入组件,否则这可能是不可行的。或者您可以假设它不是函数或字符串,那么它是一个组件,但这很难看。另一种选择是为字符串、函数和组件分别输入,并使用正确的。
  • 你这样做是有原因的吗? this 会起作用吗?

标签: angular typescript angular2-template transclusion


【解决方案1】:

看起来这是可行的:

private getTypeOf(d:any): string {
  let type:string = typeof d;
  if (type === 'function') {
    let metaKeys:string = Reflect.getMetadataKeys(d);
    if (metaKeys.indexOf('annotations') > 0) {
      let annotations:string[] = Reflect.getMetadata('annotations', d);
      if (annotations.indexOf('@Component') > 0) {
        type = '@Component';
      }
    }
  }
  return type;
}

更多详情请查看Reflect documentation

请注意,这不适用于 Internet Explorer。

编辑 metadata 方法文档在一夜之间神秘地从 MDN 网站上消失了,你可以看看 this website 代替

【讨论】:

    猜你喜欢
    • 2018-05-19
    • 2022-01-09
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 2013-08-26
    相关资源
    最近更新 更多