Home > Software engineering >  Angular - Clear Input text when click on "x"
Angular - Clear Input text when click on "x"

Time:05-03

I have an Input field where user can enter text. I have a x symbol to the left of input field. I am trying to clear text when symbol is clicked but unable to do so. Also input tfFormInput is custom text from npm library

I have tried using ngModel but did not work for me

What should I add in remove method to make it work? enter image description here

  <div ><input tfFormInput />
    </div>


    <div  (click)="remove()"  [(ngModel)]="searchValue">
        <div >
            <svg viewBox="0 0 10 10">
                <line x1="1" y1="1" x2="9" y2="9"/>
                <line x1="1" y1="9" x2="9" y2="1"/>
            </svg>
        </div>
    </div>

.ts

export class SearchComponent implements OnInit {

  searchValue:string = '';


 removeSelectedSpecification(){
    this.searchValue = '';

  }
}

CodePudding user response:

NgModel should be on input like below.

<div ><input tfFormInput [(ngModel)]="searchValue"/>
    </div>


    <div  (click)="remove()">
        <div >
            <svg viewBox="0 0 10 10">
                <line x1="1" y1="1" x2="9" y2="9"/>
                <line x1="1" y1="9" x2="9" y2="1"/>
            </svg>
        </div>
    </div>


remove() { this.searchValue = ''; }

CodePudding user response:

you could try something like this. move the searchValue to the input element.

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="text" placeholder="Search..." [(ngModel)]="searchValue">
      <button (click)="clearSearch()">Clear</button>
    </div>
  `,
})
export class App {
  searchValue:string = null;
  clearSearch() { 
    this.searchValue = '';
    console.log(this.searchValue.length, this.searchValue, typeof(this.searchValue));
  }
} 
  • Related