Issue
I'm trying to use CSS3 animation in my template, but I'm trying to find a away to add and remove class using (click)='function()' like jQuery way.
Question is how can I do the function below which is a jQuery in Angular 2?
This is what I have at the moment in my SharedService. I believe that you can't use Renderer angular core component in the service. Reason this is in a service is so other components can use it.
openBasketView() {
$('#basketView').removeClass('fadeOutRight');
$('#basketView').addClass('fadeInRight');
}
closeBasketView() {
$('#basketView').removeClass('fadeInRight');
$('#basketView').addClass('fadeOutRight');
}
Rather than using something like -- I like using function in (click) event is better and readable as all logic is in a block function.
component boolean
public showThis: Boolean = false;
template view
<div class="basket animated" [ngClass]="{'myClass': showThis}"> </div>
<button (click)="showThis = !showThis"></button>
Solution
If the display logic is in a service injected in the component, you can call the service from the template to add the toggled class. Additionally, if you want to turn on block display after clicking the button, you can put that logic in the component or in the service (in the example below, that code is in the component).
The component:
class MyComponent {
private displayBlock = false;
private turnOnBlockDisplay() {
this.displayBlock = true;
}
private getBlockClass() {
return this.displayBlock ? "block" : "";
}
constructor (private myService: ToggleClassService, ...) {
...
}
...
}
The service:
class ToggleClassService {
private fadeIn = false;
public toggleClass() {
this.fadeIn = !this.fadeIn;
}
public getClass() {
return this.fadeIn ? "fadeInRight" : "fadeOutRight";
}
}
The template:
<div [ngClass]="['basket', 'animated', myService.getClass(), getBlockClass()]">...</div>
<button (click)="myService.toggleClass(); turnOnBlockDisplay();">Toggle</button>
The CSS:
.basket {
display: inline-block;
...
}
.basket.fadeInRight {
background-color: red;
}
.basket.fadeOutRight {
background-color: blue;
}
.basket.block {
display: block;
}
You can test the code in this codepen (note: the "service" is not injected).
Answered By - ConnorsFan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.