Skip to content

Instantly share code, notes, and snippets.

@roshanca
Forked from pdib/loading.ts
Created November 24, 2015 15:18
Show Gist options
  • Save roshanca/af357c8530c7db07f317 to your computer and use it in GitHub Desktop.
Save roshanca/af357c8530c7db07f317 to your computer and use it in GitHub Desktop.
Create a loading spinner that disappears once the content is loaded with Angular 2.
@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) {
if (newValue) {
if (this._spinnerComponent) {
this._spinnerComponent.dispose();
}
this._viewContainer.createEmbeddedView(this._templateRef);
} else {
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