Home > OS >  How can I show a div whenever I write in an input? Angular 12
How can I show a div whenever I write in an input? Angular 12

Time:06-03

I've created a boolean variable isClearShown: boolean = false; In my TS component, And i want to toggle the Clear div whenever the input is being written. I have used *ngIf, and its not working.

This is the code:

The input:

<input type="search" #inputSearch placeholder="Search networks, applications, and more" value="" name="s" title="" />

and the div i want to hide whenever the input is being written:

<div (click)="clearSearch()" [hidden]="isClearShown" *ngIf="isClearShown" >Clear</div>

      <input type="search"  #inputSearch placeholder="Search networks, applications, and more" value="" name="s" title="" />
Clear

CodePudding user response:

You need to modify your code to something like this:

<div (click)="clearSearch()" *ngIf="value != ''" >Clear</div>
<input type="search"  #inputSearch placeholder="Search networks, applications, and more" [(value)]="value" name="s" title="" />

In TS file :

value:string = "";

The value variable will contain the current value of the input field. On change of that, your div will automatically enable or disable

CodePudding user response:

The usage of [hidden]="condition" and *ngIf="condition" in the same div is not correct. You should use either of them not both. *ngIf expects an opposite condition to hidden property which is native to html. hidden just masks the element from the UI but it keeps it in the DOM. *ngIf however removes the element from the DOM and it is specific to Angular. With this being said you need to toggle the boolean value of the property passed either to hidden or *ngIf. That can be done but a variety of ways such as:

1- (blur) and (focus) in the input field

2- length of string in input field

You have to specify what you are doing so we can point you to the right direction.

I assume you are using a form (whether reative or template-driven) from @Angular/forms.

  • Declare a formGroup and formControl and connect them both in TS file and HTML file then set your boolean property based on the value of the input control *ngIf="inputField.value !== ''". Otherwise just do that by accessing the value of the template reference directly (The one you named #inputSearch with @ViewChild('inputSearch') inputSearch:ElementRef) .

CodePudding user response:

Here is a little example of template reference usage

     <input (keyup)="0" type="text" #lastName id="lastName">
     <div *ngIf="lastName.value != ''"> This div will appear when input has content. Here is the content of input: {{lastName.value}}</div> 
  • Related