如何在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
.