首页 > 解决方案 > 如何确定一个对象是否是 ViewRef?

问题描述

我有一个类,我在我的应用程序的多个地方使用。

import { TemplateRef } from '@angular/core';

export class ObjectPropertyDisplayStrategy<T> {
  content: TemplateRef<any> | ((record: T) => string) | string;
  displayStrategyType: DisplayStrategyType;

  constructor(content: TemplateRef<any> | ((record: T) => string) | string) {
    this.content = content;
    setDisplayStrategyType(this, content);
  }
}

从 Typescript 注释可以看出,构造函数期望传递给它的参数类型为TemplateReforFunctionString。然后它将这个参数传递给一个函数setDisplayStrategyType

function setDisplayStrategyType(
  displayStrategy: { displayStrategyType: DisplayStrategyType },
  content: TemplateRef<any> | ((record: any) => string) | string
) {
  if (Object.getPrototypeOf(content).constructor.name === 'TemplateRef_') {
    displayStrategy.displayStrategyType = DisplayStrategyType.Template;
    return;
  }

  switch (typeof content) {
    case typeof Function:
    displayStrategy.displayStrategyType = DisplayStrategyType.FunctionTransform;
      break;
    case typeof String:
    default:
    displayStrategy.displayStrategyType = DisplayStrategyType.String;
      break;
  }
}

此函数尝试确定三种类型中的哪一种作为参数传递,然后设置一个枚举值,该值允许某些显示逻辑出现在 Angular 组件中。

具体的TemplateRef类型,是通过以下逻辑来确定的:if (Object.getPrototypeOf(content).constructor.name === 'TemplateRef_'). 当我使用ng build. 但是,当我运行时ng build --prod,它停止工作,似乎是因为当一切都变得丑陋时,TemplateRef_对象变成了类似e. 此问题在此处对答案的第一条评论中提到。

我尝试使用该TemplateRef符号来处理此问题,如下所示:

const a = typeof TemplateRef;
const b = new TemplateRef();
const c = Object.getPrototypeOf(TemplateRef);

以及ViewChild装饰器,这似乎是 Angular 中创建TemplateRef实例的一种方式。

const a = typeof ViewChild;
const b = new ViewChild();
const c = Object.getPrototypeOf(ViewChild);

不过,这些策略似乎都不起作用。有没有一种可靠的方法来构造一个新TemplateRef对象,我可以将“类型”与我传递的属性进行比较,或者用另一种方法来做出这个决定,以便我的库可以继续使用产品构建?

标签: javascriptangular

解决方案


推荐阅读