angular elements in firefox "this.ngElementStrategy is undefined"

292 views Asked by At

I'm using ngx-build-plus for compile element to js.

class NgElementImpl
class NgElementImpl

Error ERROR TypeError: can't access property "events", this.ngElementStrategy is undefined throw at line 512. And the break point is fired. But the point at line 481 isn't.

Offical repo: https://github.com/angular/elements-builds/blob/12.0.x/esm2015/src/create-custom-element.js#L55

1

There are 1 answers

0
izogfif On

For some reason, createElement passes HTML element you're creating as this inside constructor of NgElementImpl instead of instance of NgElementImpl. And this this doesn't have NgElementImpl's methods or private / protected fields. The (ugly) solution would be moving all NgElementImpl internals outside of the class, into the enclosing function:

  1. Download Angular Elements sources (you can do that via Download Github Directory website).
  2. Put them into your Angular project.
  3. Modify create-custom-element.ts by moving implementation of instance methods get ngElementStrategyImpl and subscribeToEvents outside of the class.

The version below is taken (and rewritten) from Angular 17.0.6 sources.

/* eslint-disable  */

/* eslint-disable @typescript-eslint/no-unnecessary-type-assertion */
/* eslint-disable @typescript-eslint/no-unsafe-argument */
/* eslint-disable no-param-reassign */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable no-prototype-builtins */
/**
 * @license
 * Copyright Google LLC All Rights Reserved.
 *
 * Use of this source code is governed by an MIT-style license that can be
 * found in the LICENSE file at https://angular.io/license
 */

import { Injector, Type } from '@angular/core';
import { Subscription } from 'rxjs';

import { ComponentNgElementStrategyFactory } from './component-factory-strategy';
import {
  NgElementStrategy,
  NgElementStrategyFactory,
} from './element-strategy';
import {
  getComponentInputs,
  getDefaultAttributeToPropertyInputs,
} from './utils';

/**
 * Prototype for a class constructor based on an Angular component
 * that can be used for custom element registration. Implemented and returned
 * by the {@link createCustomElement createCustomElement() function}.
 *
 * @see [Angular Elements Overview](guide/elements "Turning Angular components into custom elements")
 *
 * @publicApi
 */
export interface NgElementConstructor<P> {
  /**
   * An array of observed attribute names for the custom element,
   * derived by transforming input property names from the source component.
   */
  readonly observedAttributes: string[];

  /**
   * Initializes a constructor instance.
   * @param injector If provided, overrides the configured injector.
   */
  new (injector?: Injector): NgElement & WithProperties<P>;
}

/**
 * Implements the functionality needed for a custom element.
 *
 * @publicApi
 */
export abstract class NgElement extends HTMLElement {
  /**
   * The strategy that controls how a component is transformed in a custom element.
   */
  protected abstract getngElementStrategy(): NgElementStrategy;
  /**
   * A subscription to change, connect, and disconnect events in the custom element.
   */
  protected ngElementEventsSubscription: Subscription | null = null;

  /**
   * Prototype for a handler that responds to a change in an observed attribute.
   * @param attrName The name of the attribute that has changed.
   * @param oldValue The previous value of the attribute.
   * @param newValue The new value of the attribute.
   * @param namespace The namespace in which the attribute is defined.
   * @returns Nothing.
   */
  abstract attributeChangedCallback(
    attrName: string,
    oldValue: string | null,
    newValue: string,
    namespace?: string
  ): void;
  /**
   * Prototype for a handler that responds to the insertion of the custom element in the DOM.
   * @returns Nothing.
   */
  abstract connectedCallback(): void;
  /**
   * Prototype for a handler that responds to the deletion of the custom element from the DOM.
   * @returns Nothing.
   */
  abstract disconnectedCallback(): void;
}

/**
 * Additional type information that can be added to the NgElement class,
 * for properties that are added based
 * on the inputs and methods of the underlying component.
 *
 * @publicApi
 */
export type WithProperties<P> = {
  [property in keyof P]: P[property];
};

/**
 * A configuration that initializes an NgElementConstructor with the
 * dependencies and strategy it needs to transform a component into
 * a custom element class.
 *
 * @publicApi
 */
export interface NgElementConfig {
  /**
   * The injector to use for retrieving the component's factory.
   */
  injector: Injector;
  /**
   * An optional custom strategy factory to use instead of the default.
   * The strategy controls how the transformation is performed.
   */
  strategyFactory?: NgElementStrategyFactory;
}

/**
 *  @description Creates a custom element class based on an Angular component.
 *
 * Builds a class that encapsulates the functionality of the provided component and
 * uses the configuration information to provide more context to the class.
 * Takes the component factory's inputs and outputs to convert them to the proper
 * custom element API and add hooks to input changes.
 *
 * The configuration's injector is the initial injector set on the class,
 * and used by default for each created instance.This behavior can be overridden with the
 * static property to affect all newly created instances, or as a constructor argument for
 * one-off creations.
 *
 * @see [Angular Elements Overview](guide/elements "Turning Angular components into custom elements")
 *
 * @param component The component to transform.
 * @param config A configuration that provides initialization information to the created class.
 * @returns The custom-element construction class, which can be registered with
 * a browser's `CustomElementRegistry`.
 *
 * @publicApi
 */
export function createCustomElement<P>(
  component: Type<any>,
  config: NgElementConfig
): NgElementConstructor<P> {
  const inputs = getComponentInputs(component, config.injector);

  const strategyFactory =
    config.strategyFactory ||
    new ComponentNgElementStrategyFactory(component, config.injector);

  const attributeToPropertyInputs = getDefaultAttributeToPropertyInputs(inputs);
  let _ngElementStrategy: NgElementStrategy | undefined;

  function getngElementStrategyImpl(
    that: NgElement,
    injector?: Injector
  ): NgElementStrategy {
    // TODO(andrewseguin): Add e2e tests that cover cases where the constructor isn't called. For
    // now this is tested using a Google internal test suite.
    if (!_ngElementStrategy) {
      const strategy = (_ngElementStrategy = strategyFactory.create(
        injector || config.injector
      ));

      // Re-apply pre-existing input values (set as properties on the element) through the
      // strategy.
      inputs.forEach(({ propName, transform }) => {
        if (!that.hasOwnProperty(propName)) {
          // No pre-existing value for `propName`.
          return;
        }

        // Delete the property from the instance and re-apply it through the strategy.
        const value = (that as any)[propName];
        delete (that as any)[propName];
        strategy.setInputValue(propName, value, transform);
      });
    }

    return _ngElementStrategy!;
  }
  let ngElementEventsSubscription: Subscription | null = null;
  function subscribeToEvents(): void {
    if (!instance) {
      return;
    }
    // Listen for events from the strategy and dispatch them as custom events.
    ngElementEventsSubscription = getngElementStrategyImpl(
      instance,
      instance.injector
    ).events.subscribe(e => {
      const customEvent = new CustomEvent(e.name, { detail: e.value });
      instance!.dispatchEvent(customEvent);
    });
  }
  let instance: NgElementImpl | undefined;
  class NgElementImpl extends NgElement {
    // Work around a bug in closure typed optimizations(b/79557487) where it is not honoring static
    // field externs. So using quoted access to explicitly prevent renaming.
    static readonly ['observedAttributes'] = Object.keys(
      attributeToPropertyInputs
    );

    protected override getngElementStrategy(): NgElementStrategy {
      if (!instance) {
        throw new Error('Illegal state');
      }
      return getngElementStrategyImpl(instance, instance.injector);
    }

    // private _ngElementStrategy?: NgElementStrategy;

    constructor(public readonly injector?: Injector) {
      super();
      instance = this;
    }

    override attributeChangedCallback(
      attrName: string,
      oldValue: string | null,
      newValue: string,
      namespace?: string
    ): void {
      if (!instance) {
        throw new Error('Illegal state');
      }
      const [propName, transform] = attributeToPropertyInputs[attrName]!;
      getngElementStrategyImpl(instance, instance.injector).setInputValue(
        propName,
        newValue,
        transform
      );
    }

    override connectedCallback(): void {
      // For historical reasons, some strategies may not have initialized the `events` property
      // until after `connect()` is run. Subscribe to `events` if it is available before running
      // `connect()` (in order to capture events emitted during initialization), otherwise subscribe
      // afterwards.
      //
      // TODO: Consider deprecating/removing the post-connect subscription in a future major version
      //       (e.g. v11).

      let subscribedToEvents = false;
      if (!instance) {
        return;
      }

      if (getngElementStrategyImpl(instance, instance.injector).events) {
        // `events` are already available: Subscribe to it asap.
        subscribeToEvents();
        subscribedToEvents = true;
      }

      getngElementStrategyImpl(instance, instance.injector).connect(instance);

      if (!subscribedToEvents) {
        // `events` were not initialized before running `connect()`: Subscribe to them now.
        // The events emitted during the component initialization have been missed, but at least
        // future events will be captured.
        subscribeToEvents();
      }
    }

    override disconnectedCallback(): void {
      if (!instance) {
        return;
      }
      // Not using `this.ngElementStrategy` to avoid unnecessarily creating the `NgElementStrategy`.
      if (_ngElementStrategy) {
        _ngElementStrategy.disconnect();
      }

      if (ngElementEventsSubscription) {
        ngElementEventsSubscription.unsubscribe();
        ngElementEventsSubscription = null;
      }
    }
  }

  // Add getters and setters to the prototype for each property input.
  inputs.forEach(({ propName, transform }) => {
    Object.defineProperty(NgElementImpl.prototype, propName, {
      get(): any {
        if (!instance) {
          return;
        }
        return getngElementStrategyImpl(
          instance,
          instance.injector
        ).getInputValue(propName);
      },
      set(newValue: any): void {
        if (!instance) {
          return;
        }
        getngElementStrategyImpl(instance, instance.injector).setInputValue(
          propName,
          newValue,
          transform
        );
      },
      configurable: true,
      enumerable: true,
    });
  });

  return NgElementImpl as any as NgElementConstructor<P>;
}
  1. Use createCustomElement from this modified create-custom-element.ts instead of importing it from Angular Elements.
  2. Remove version.ts from copy-pasted Angular Elements sources.

You might need to either add "noImplicitAny": false, to your tsconfig.app.json, or to further adjust the source code to avoid compilation errors. Also, consider adding /* eslint-disable */ to the top of each copy-pasted Angular Elements files to avoid linter errors.

The related bug in Angular repository was marked as fixed, but it still strikes back at you in Firefox 120 as of 2023-12-11.