-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
}); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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