How To Change Background By Clicking A Button?
Solution 1:
Use [style.background]
:
(I created demo:https://stackblitz.com/edit/ionic-mgbhjq?file=pages%2Fhome%2Fhome.html)
<div id="back" class="ion-content" [style.background]="'url('+image+')'"></div>
<button id="transparent" ion-button round color="light" (click)="changeImage()"> </button>
TS(component)
image:any;
ngOnInit(){
this.image ="your first url";
}
changeImage(){
this.image="your second url";
}
TO your comment:
integrate an id for my second background
use attr.id
:
<divattr.id="idParam"class="ion-content" [style.background]="'url('+image+')'"></div>
TS(component)
image:any;
idParam:string="back";
ngOnInit(){
this.image ="your first url";
}
changeImage(){
this.image="your second url";
this.idParam="secondBack";
}
Solution 2:
Ionic uses Angular under the hood. So best way to handle the event is in controller of your view. So in your 'YourController.ts' file you need to write handler method like this:
changeBackground() {
this.image = '<url_of_new_image>';
}
Then you can use this event in your button like this:
<button id="transparent" ion-button round color="light" (click)="changeBackground()"> </button>
Above is simple angular way of binding event to handler method. Now we can use Angular attribute binding to bind style attribute to 'image' property like this:
<div id="back" class="ion-content" [style.background]="'url('+image+')'"></div>
So basically when user will click your button then following things will happen:
- changeBackground() method of
YourController.ts
will be called. - Here we are setting property
image
to new value. - So DOM manipulation of Angular will change div background to this new value.
- New image replaces existing image.
To all those who are still wondering why Angular is being used here can watch this: Ionic Intro and Crash course
Post a Comment for "How To Change Background By Clicking A Button?"