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

眉间皱痕 提交于 2019-12-22 15:49:12

问题


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() {
  document.body.appendHtml('<web-sandbox-component></web-sandbox-component>');
  var node = document.body.query('web-sandbox-component');
  ng.compile(node);
}

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?


回答1:


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?.

EDIT

Your code in main should look like this:

my document looks like

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

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

main() {
  print('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);
}


来源:https://stackoverflow.com/questions/23184009/angular-dart-how-to-create-a-custom-component-programmatically-and-add-to-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!