如何在Angular.Dart中以编程方式添加组件? [英] How to add a component programmatically in Angular.Dart?

查看:75
本文介绍了如何在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 programmatically 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]); 
  }

}

推荐答案

这将是对Block 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中以编程方式添加组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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