Creating a dynamic angular component dynamically

I am trying to create a dynamic angular component dynamically. I know this is not the best practice, but I have to because of how my angular widgets are inserted.

I based my work:

How to add a component programmatically in Angular.Dart?

Code examples for longer work due to changes in the Dart angular library.

This code works for me, but it is incompatible. The solution was Timer.run () to run scope.apply. The problem with this:

  • It stinks to make such a call and will work terribly with lots of components.
  • This seems to work randomly. He does most of the time, but sometimes he doesn’t {{foo}} replace
void main() {
  IBMModule module = new IBMModule();
  AngularModule angularModule = new AngularModule();

  Injector injector = applicationFactory()
  .addModule(module)
  .run();

  AppComponent appComponent = injector.get(AppComponent);
  appComponent.addElement("<brazos-input-string label='test'/>");
}

class MyValidator implements NodeValidator {


  bool allowsElement(Element element) {
    return true;
  }

  bool allowsAttribute(Element element, String attributeName, String value) {
    return true;
  }

}

@Injectable()
class AppComponent {
  NodeValidator validator;
  Compiler _compiler;
  DirectiveInjector _directiveInjector;
  DirectiveMap _directiveMap;
  NodeTreeSanitizer _nodeTreeSanitizer;
  Injector _appInjector;
  Scope _scope;

  AppComponent(this._directiveInjector, this._compiler, this._directiveMap, this._nodeTreeSanitizer, this._appInjector, this._scope) {
    validator = new MyValidator();
  }

  void addElement(String elementHTML) {
    DivElement container = querySelector("#container");
    DivElement inner = new DivElement();
    container.append(inner);
    Element element = new Element.html(elementHTML, validator: validator);
    // inner.setInnerHtml(elementHTML, validator: validator);
    ViewFactory viewFactory = _compiler.call([element], _directiveMap);
    if (_scope != null) {
      Scope childScope = _scope.createProtoChild();
      View newView = viewFactory.call(childScope, _directiveInjector);
      newView.nodes.forEach((node) => inner.append(node));
      Timer.run(() => childScope.apply());
    } else {
      print("scope is null");
    }
  }
}


class IBMModule extends Module {
  IBMModule() {
    bind(BrazosInputStringComponent);
    bind(BrazosTextAreaComponent);
    bind(BrazosButtonComponent);
    bind(ProcessDataProvider, toImplementation: ActivitiDataProvider);
    bind(AppComponent);
  }
}
+4
source share

All Articles