Lazy image loader for Angular 2
About 90 loc and no dependencies (except for angular and rxjs of course)
Demo: http://tjoskar.github.io/ng2-lazyload-image/
The browser you targeting need to have support of WeepMap
. If you need to support an older browser (like IE or Safari) you will need to include polyfill for WeekMap
(see https://github.com/zloirock/core-js for example).
$ npm install ng2-lazyload-image --save
And then include it in your module (see app.module.ts):
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LazyLoadImageModule } from 'ng2-lazyload-image';
import { AppComponent } from './app.component';
@NgModule({
declarations: [ AppComponent ],
imports: [ BrowserModule, LazyLoadImageModule ],
bootstrap: [ AppComponent ]
})
export class MyAppModule {}
import { Component } from '@angular/core';
@Component({
selector: 'image',
template: `
<img [src]="defaultImage" [lazyLoad]="image" [offset]="offset">
`
})
class ImageComponent {
defaultImage = 'https://www.placecage.com/1000/1000';
image = 'https://images.unsplash.com/photo-1443890923422-7819ed4101c0?fm=jpg';
offset = 100;
}
It also supports background images, by using backgroundImage
:
@Component({
selector: 'image',
template: `
<div [src]="defaultImage" [lazyLoad]="image" [offset]="offset"></div>
<!--
After it has been loaded the div will transform into:
<div class="ng2-lazyloaded" style="background-image: url('https://images.unsplash.com/photo-1443890923422-7819ed4101c0?fm=jpg');"></div>
-->
`
})
class ImageComponent {
defaultImage = 'https://www.placecage.com/1000/1000';
image = 'https://images.unsplash.com/photo-1443890923422-7819ed4101c0?fm=jpg';
offset = 100;
}
See example folder for more usages.
Run unit
tests:
$ npm test
Run e2e
tests:
$ npm run webdriver:update
$ npm run e2e