angular.dart how to create a custom component programmatically and add to page?


Is it possible to define an angular-dart component and then programmatically create an instance of that component and add it to your web page? I’d hoped there might be something like:

import 'package:web_sandbox/web_sandbox.dart';
import 'package:angular/angular.dart' as ng;

void main() {
  var node = document.body.query('web-sandbox-component');

is there away of creating an angular web component programmatically and adding it to the page, maybe like the above pseudo-example, and if so how?


I don’t think this is possible with Angular.

You can add an HTML tag <web-sandbox-component> into the DOM and tell Angular it should process this new HTML and then Angular would instantiate the Angular component for this tag (this is what the question you linked is about).

I don’t see this as a limitation.
Is there something you would like to do that seems not possible this way?.


Your code in main should look like this:

my document looks like

  <div id="mydiv"></div>

and I append the <web-sandbox-component> to the div

main() {
  ng.Injector inj = ngaf.applicationFactory().addModule(new MyAppModule()).run();
  var node = dom.querySelector('#mydiv');
  node.append(new dom.Element.html('<web-sandbox-component></web-sandbox-component>', validator: new dom.NodeValidatorBuilder()..allowCustomElement("web-sandbox-component")));
  ng.Compiler compiler = inj.get(ng.Compiler);
  ng.DirectiveMap directiveMap = inj.get(ng.DirectiveMap);
  compiler(node.childNodes, directiveMap)(inj, node.childNodes);

Answered By – Günter Zöchbauer

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *