Reputation: 11
Below is my input field and I have a class(form--cross) with background image cross(x) in this input form. I want to hide/show the cross icon (Class = "form--cross")based on the Keypress however i have no idea how to do it in angular4.
<div class="form">
<input [(ngModel)]="templateSearch" type="text" id="search" placeholder="search" class="form--cross" autofocus>
<button class="btn" (click)="search()"></button>
</div>
Upvotes: 0
Views: 791
Reputation: 2999
In your template (HTML):
<div class="form">
<input #searchInput [(ngModel)]="templateSearch" type="text" id="search" placeholder="search"
[class.form--cross]="searchInput.value.length == 0" autofocus>
<button class="btn" (click)="search()"></button>
</div>
If you want to hide the cross (hide the class) when the input is losing focus, that is a different kind of question.
If you want to clear the input when you click on the cross, that's a little difficult thing, because you're using CSS for displaying the cross.
If you want to use the exact same cross that you linked in your comment, you can use type="search"
for your input.
Upvotes: 1
Reputation: 21367
you need to listen to keyup or input event in the input, and bind your ngClass that way [ngClass]="{'form--cross': isWriting}"
<input [(ngModel)]="templateSearch" (input)="onKey($event)" type="text" id="search" placeholder="search" [ngClass]="{'form--cross': isWriting}" autofocus >
onKey(event) {
this.isWriting = true;
}
Upvotes: 0
Reputation: 36703
Declare a variable in .ts and then add / change class using ngClass
which will take the variable as value and class name as key:
In your component.ts
showIcon = true;
In your component.html
<input
[(ngModel)]="templateSearch"
type="text"
id="search"
placeholder="search"
(change)="showIcon=false"
ngClass="{
'form--cross': showIcon
}"
autofocus
>
Upvotes: 0