且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

angular.dart 如何以编程方式创建自定义组件并添加到页面?

更新时间:2023-09-23 18:38:52

我认为 Angular 不可能做到这一点.

I don't think this is possible with Angular.

你可以在 DOM 中添加一个 HTML 标签 并告诉 Angular 它应该处理这个新的 HTML,然后 Angular 会为这个标签实例化 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?.

编辑

您在 main 中的代码应如下所示:

Your code in main should look like this:

我的文档看起来像

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

然后我将 附加到 div

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);
}