本文介绍了如何在Angular.Dart中编程添加组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想动态构建基于从AJAX调用接收的一些信息的组件树。

I would like to dynamically build a component tree basing on some information received from AJAX calls.

如何以编程方式从其他组件内部向DOM中添加组件?我有< outer-comp> ,我想基于一些逻辑,插入< inner-comp> 。下面的代码只是将元素< inner-comp>< / inner-comp> 插入到DOM中,而不是实际的< inner- comp> 表示。

How to programatically add a component to the DOM from inside of other component? I have <outer-comp> and I would like, basing on some logic, insert an <inner-comp>. The following code just inserts the elements <inner-comp></inner-comp> to the DOM, and not actual <inner-comp> representation.

@NgComponent(
  selector: 'outer-comp',
  templateUrl: 'view/outer_component.html',
  cssUrl: 'view/outer_component.css',
  publishAs: 'outer'
)
class AppComponent extends NgShadowRootAware {
  void onShadowRoot(ShadowRoot shadowRoot) {
    DivElement inner = shadowRoot.querySelector("#inner");
    inner.appendHtml("<inner-comp></inner-comp>");
  }
}

更新:
我设法以下面的方式正确地渲染内部组件,但我仍然不确定这是否是正确的方式:

Update:I managed to render the inner component correctly in the following way, but I'm still not sure if this is the proper way:

class AppComponent extends NgShadowRootAware {
  Compiler compiler;
  Injector injector;
  AppComponent(this.compiler, this.injector);

  void onShadowRoot(ShadowRoot shadowRoot) {
    DivElement inner = shadowRoot.querySelector("#inner");
    inner.appendHtml("<inner-comp></inner-comp>");
    BlockFactory template = compiler(inner.nodes);
    var block = template(injector);
    inner.replaceWith(block.elements[0]);
  }

}

推荐答案

这将是正确使用块API。

This would be a proper use of the block API.

class AppComponent extends NgShadowRootAware {
  Compiler compiler;
  Injector injector;
  Scope scope;
  DirectiveMap directives;

  AppComponent(this.compiler, this.injector, this.scope, this.directives);

  void onShadowRoot(ShadowRoot shadowRoot) {
    DivElement inner = shadowRoot.querySelector("#inner");
    inner.appendHtml("<inner-comp></inner-comp>");
    BlockFactory template = compiler([inner], directives);
    Scope childScope = scope.$new();
    Injector childInjector =
        injector.createChild(new Module()..value(Scope, childScope));
    template(childInjector, [inner]);
  }
}

此外,如果您需要重新编译内部模板请确保您对上一个 childScope 执行 childScope。$ destroy()

Also, if you ever need to recompile the inner template make sure you do childScope.$destroy() on the previous childScope.

这篇关于如何在Angular.Dart中编程添加组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:34