Skip to content

Instantly share code, notes, and snippets.

@pdib
Last active November 25, 2015 18:35
Show Gist options
  • Save pdib/0b2e87c31525fdfbe797 to your computer and use it in GitHub Desktop.
Save pdib/0b2e87c31525fdfbe797 to your computer and use it in GitHub Desktop.
Create a loading spinner that disappears once the content is loaded with Angular 2.
import { Component, ComponentRef, Directive, DynamicComponentLoader, TemplateRef, ViewContainerRef } from 'angular2/angular2';
@Component({
selector: 'spinner',
template: `<h1>spinner</h1>` // This will be displayed while loading.
})
class Spinner {
}
@Directive({
selector: "[loading]",
inputs: ["loading"],
})
export class Loading {
private _spinnerComponent: ComponentRef;
constructor(private dcl: DynamicComponentLoader,
private _viewContainer: ViewContainerRef,
private _templateRef: TemplateRef) {}
set loading(newValue: any) {
this._viewContainer.clear();
if (newValue) {
if (this._spinnerComponent) {
this._spinnerComponent.dispose();
}
this._viewContainer.createEmbeddedView(this._templateRef);
} else {
// This creates the spinner and inserts it next to _viewContainer.
// Note that you can use another Spinner class with Dependency Injection:
// - add a provider for the Spinner class ( `provide(Spinner, { useClass: MySpinner });` )
// - inject it into the `Loading` directive
// - in the following line, replace `Spinner` by `this._injectedSpinner.constructor`
this.dcl.loadNextToLocation(Spinner, this._viewContainer.element).then((spinner: ComponentRef) => {
this._spinnerComponent = spinner;
});
}
}
}
import { MyService } from 'service'; // this is yours to define
import { Loading } from 'loading';
@Component({
selector: 'user-profile'
})
@View({
// Specify what has to be loaded.
// As soon `serviceData` evaluates to true, the spinner disappears and the <span> is displayed
// You can use a boolean variable or some other data as a flag for *loading.
template: `
<div *loading="serviceData">
<span>User: {{serviceData.user}}</span>
</div>
`,
directives: [Loading]
})
class MyComponent {
public serviceData: any;
constructor(private myService: MyService) {
this.myService.fetch().then((serviceData: any) => {
this.serviceData = serviceData;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment