Created
May 24, 2016 06:33
-
-
Save fer-ri/314cd43a32a417f176d39a6084af5829 to your computer and use it in GitHub Desktop.
Background Image Style Directive for Angular 2 and Ionic 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
import {Directive, ElementRef, Input} from '@angular/core'; | |
@Directive({ | |
selector: '[background-image]' | |
}) | |
export class BackgroundImage { | |
private el: HTMLElement; | |
constructor(el: ElementRef) { | |
this.el = el.nativeElement; | |
} | |
@Input('background-image') backgroundImage: string; | |
ngAfterViewInit() { | |
this.el.style.backgroundImage = 'url(' + this.backgroundImage + ')'; | |
} | |
} |
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
<div class="header" background-image="{{ item.featured_image }}"> | |
<!--some content--> | |
</div> | |
<!-- alternative --> | |
<div class="header" [ngStyle]="{'background-image': 'url(' + item.featured_image + ')'}"> | |
<!--some content--> | |
</div> |
Thanks, very useful!
For those on Ionic3 that used ionic generate directive backgroundImage
to add this code, don't forget to:
import { DirectivesModule } from '../directives/directives.module';
and then add it into the app.module.ts imports, eg:
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule,
DirectivesModule
], (...)
angular 8
I do this on
app.ts
this.backgroudImage = { "background-image":
url('${data.background_image}') };
and this in
app.html
<section class="jumbotron" [ngStyle]="backgroudImage"> <div class="container"> <div class="row text-center"> <h2>{{Game?.name}}</h2> </div> </div> </section>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Después de haber usado esta directiva por un tiempo, me di cuenta de que hay un problema cuando la imagen que le paso al
Input
es asíncrona, así que lo solucioné agregandongOnChages
para manejar los futuros cambios en elInput
. También use elRenderer2
como recomendación de este post.Espero sea de utilidad 😄