Elaine
Elaine

Reputation: 41

How to programmatically add a created component to Page?

I want to use a self-created component, and dynamically add it to the page.

It works well in static ways, such as adding it directly in html as <My-Component></My-Component>.

When it comes to dynamic ways, I first tried to directly use:

  var node = document.body.query('#board');
  node.append( new Element.html('<My-Component></My-Component>'));

It just display nothing because cannot parse the created component.

There is a way in dart v1 to do this dynamically like:

  ng.Injector inj = ngaf.applicationFactory().addModule(new MyAppModule()).run();
  var node = dom.querySelector('#mydiv');
  node.append(new dom.Element.html('<My-Component></My-Component>', validator: new dom.NodeValidatorBuilder()..allowCustomElement("My-Component")));
  ng.Compiler compiler = inj.get(ng.Compiler);
  ng.DirectiveMap directiveMap = inj.get(ng.DirectiveMap);
  compiler(node.childNodes, directiveMap)(inj, node.childNodes);

How could this be implemented in current Dart? Or where can 'Compiler', 'DirectiveMap'etc. be found?

Upvotes: 0

Views: 770

Answers (1)

Chellappan வ
Chellappan வ

Reputation: 27439

HTML

    <ng-container #vc></ng-container>  

TS

    @ViewChild('vc',{read:ViewContainerRef}) vc:ViewContainerRef;        
    constructor(private resolver:ComponentFactoryResolver){        
    const factory=this.resolver.resolveComponentFactory(Component)
    //This code used to get component factory
    this.vc.clear()
    //Clear ViewContainer
    this.vc.createComponent(factory);

}

Example:https://stackblitz.com/edit/angular-dynamically-creating-components-pakc72 Documentation:https://angular.io/guide/dynamic-component-loader

Upvotes: 1

Related Questions