angular.dart 如何以编程方式创建自定义组件并添加到页面? [英] angular.dart how to create a custom component programmatically and add to page?

查看:30
本文介绍了angular.dart 如何以编程方式创建自定义组件并添加到页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以定义一个 angular-dart 组件,然后以编程方式创建该组件的实例并将其添加到您的网页中?我希望可能有类似的东西:

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

是否可以通过编程方式创建一个 Angular Web 组件并将其添加到页面中,也许就像上面的伪示例,如果是这样,如何?

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?

推荐答案

我认为 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);
}

这篇关于angular.dart 如何以编程方式创建自定义组件并添加到页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆