17.10.2018 Views

Angular

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

templateUrl: './app/app.component.html',<br />

styleUrls: ['./app/app.component.css'],<br />

entryComponents: [ChartWidget, DataWidget],<br />

})<br />

export class AppComponent {<br />

private elements: Array=[];<br />

private WidgetClasses = {<br />

'ChartWidget': ChartWidget,<br />

'DataWidget': DataWidget<br />

}<br />

@ViewChild(DynamicComponent) dynamicComponent:DynamicComponent;<br />

addComponent(widget: string ): void{<br />

let ref= this.dynamicComponent.addComponent(this.WidgetClasses[widget]);<br />

this.elements.push(ref);<br />

console.log(this.elements);<br />

}<br />

}<br />

this.dynamicComponent.resetContainer();<br />

app.component.html<br />

Add ChartWidget<br />

Add DataWidget<br />

<br />

<br />

Dynamic Components<br />

<br />

<br />

{{item}}<br />

<br />

<br />

<br />

https://plnkr.co/edit/lugU2pPsSBd3XhPHiUP1?p=preview<br />

Some modification by @yurzui to use mouse event on the widgets<br />

view.directive.ts<br />

import { ViewRef, Directive, Input, ViewContainerRef } from '@angular/core';<br />

@Directive({<br />

selector: '[view]'<br />

})<br />

export class ViewDirective {<br />

constructor(private vcRef: ViewContainerRef) {}<br />

@Input()<br />

set view(view: ViewRef) {<br />

this.vcRef.clear();<br />

this.vcRef.insert(view);<br />

}<br />

ngOnDestroy() {<br />

this.vcRef.clear()<br />

GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 56

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!