2

Background info: There is a fairly common problem that was previously brought up in this github issue about an injector error when using UpgradeComponents inside of dynamically loaded entry components. I feel that I understand this well enough, and have been able to get the scope injected properly by using a similar solution to this answer:

export const ScopeProvider = {
  deps: ['$injector'],
  provide: '$scope',
  useFactory: scopeFunction,
};

export function scopeFunction(i: any) {
  const newScope = i.get('$rootScope').$new();

  // special property to differentiate this scope from the one coming
  // from the injector that is not used for dynamically loaded components
  newScope.dynamicScope = true;

  return newScope;
}

I definitely would like to know if there are pitfalls to this solution that I'm not aware of, as opposed to the injector solution mentioned in the github issue.

However, that is not my main concern. My main concern is that even with the correct Injector and Scope, the UpgradeComponent still has an issue where the initial values on the component are not being detected by angularjs, because there is no $digest happening after the component gets created. It's possible that this is specifically a problem with the component loader in ngx-bootstrap, and not a general problem with angular, but I'm not sure at this point. The fix I came up with for now is to call Scope.$evalAsync() at the end of the constructor for the UpgradeComponent, but I'm not sure if this is the right way to go, which is why I am asking this question.

This is an example of the logic for my fix:

export class Testng1ComponentFacade extends UpgradeComponent implements OnInit {

  constructor(elementRef: ElementRef, injector: Injector) {
    super(testng1Component.selector, elementRef, injector);

    const injectorScope = injector.get('$scope');
    if(injectorScope.dynamicScope) {
      console.log('calling $evalAsync() for UpgradeComponent');
      injectorScope.$evalAsync(() => {});
    }
  }

}

I kinda based it off of this angular code.

TL;DR: Here's a simple repro of the issue as well, with my fix included.

CShark
  • 1,562
  • 1
  • 16
  • 27

0 Answers0