使用AoT时ViewChild找不到元素

时间:2019-03-28 08:23:44

标签: angular angular-cli angular-aot

我找到了一个很棒的装饰器,想要在我的项目中使用。但是,使用AoT时,ViewChild无法正常工作。一个老问题了,那里有很多张公开票。

import { ElementRef, ViewChild } from '@angular/core';

/**
 * To get the native element instead of ElementRef.nativeElement
 * Caveats: it won’t work with AOT
 * @param selector Selector. Example: <div #selector></div>
 */
export function NativeElement(selector: string): PropertyDecorator {
  // Create the viewchild decorator with read: ElementRef
  const propDecoratorFn: Function = ViewChild(selector, { read: ElementRef });

  // Target is the component object
  // Property key is the name of the property
  return function(target: Object, propertyKey: string | symbol): void {
    // Somehow this will execute the viewchild process to attach a new property called tempViewChildFor_
    // to the target (component object instance)
    propDecoratorFn(target, `tempViewChildFor_${propertyKey}`);

    // Redefined the property with getter. It will return the tempViewChildFor_ with nativeElement
    Object.defineProperty(target, propertyKey, {
      get: function(): HTMLElement {
        const property = this[`tempViewChildFor_${propertyKey}`];
        if (!property) {
          throw Error(
            'Can not get ElementRef using selector, please check your component view again.'
          );
        }

        return property.nativeElement;
      }
    });
  };
}

Code source

启用AoT时是否有解决方法?

0 个答案:

没有答案