47

Why is this method not working when I try to clear the text field?

<div>
      <input type="text" placeholder="Search..." [value]="searchValue">
      <button (click)="clearSearch()">Clear</button>
</div>


export class App {
  searchValue:string = '';
  clearSearch() {
    this.searchValue = '';
  }
}

What I'm expecting: since I'm passing a property for search value, when I click the button, it should get the updated value which is processed in clearSearch() function.

I also noticed that if I set a default value to searchValue, clearSearch() function works, but only once.

Please check my plunker.

kind user
  • 40,029
  • 7
  • 67
  • 77
Body
  • 3,608
  • 8
  • 42
  • 50

10 Answers10

40

1. First Method

you have to assign null or empty string here

this.searchValue = null;
//or
this.searchValue = ' ';

Working Plunker

because no event is being fired from angular change detection. so you have to assign some value either null or string with space

2. Second Method

  • use of [(ngModel)] it should work with ngModel.

why ?

because as you did binding with value attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.

see working example of same with ngModel

Working Example with ngModel

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
  • 1
    Thank you for your reply and explanation. Second method works perfectly. Using null value, worked only the first time. Second time when I try to clear the field, it did not work. Could you please give me a picture for this behavior? – Body Jan 05 '17 at 19:13
  • glad to hear @Body, actually in case of `null` value its working first time and change the value in input field but second time it does change the value but does't reflect changes in the view/template, because there is no change detection is running by angular at that time, i.e no event binding is there, hope this clear everything – Pardeep Jain Jan 06 '17 at 05:32
  • `
    This field is Required!
    ` how to i reset the validation message as well. With above method the input gets cleared but the message shows up.
    – Sushmit Sagar Nov 03 '18 at 11:26
36

You can just change the reference of input value, as below

<div>
    <input type="text" placeholder="Search..." #reference>
    <button (click)="reference.value=''">Clear</button>
</div>
Sudheer KB
  • 1,596
  • 14
  • 28
31

There are two additional ways to do it apart from the two methods mentioned in @PradeepJain's answer.

I would suggest not to use this approach and to fall back to this only as a last resort if you are not using [(ngModel)] directive and also not using data binding via [value]. Read this for more info.

Using ElementRef

app.component.html

<div>
      <input type="text" #searchInput placeholder="Search...">
      <button (click)="clearSearchInput()">Clear</button>
</div>

app.component.ts

export class App {
  @ViewChild('searchInput') searchInput: ElementRef;

  clearSearchInput(){
     this.searchInput.nativeElement.value = '';
  }
}

Using FormGroup

app.component.html

<form [formGroup]="form">
    <div *ngIf="first.invalid"> Name is too short. </div>
    <input formControlName="first" placeholder="First name">
    <input formControlName="last" placeholder="Last name">
    <button type="submit">Submit</button>
</form>
<button (click)="setValue()">Set preset value</button>
<button (click)="clearInputMethod1()">Clear Input Method 1</button>
<button (click)="clearInputMethod2()">Clear Input Method 2</button>

app.component.ts

export class AppComponent {
  form = new FormGroup({
    first: new FormControl('Nancy', Validators.minLength(2)),
    last: new FormControl('Drew'),
  });
  get first(): any { return this.form.get('first'); }
  get last(): any { return this.form.get('last'); }
  clearInputMethod1() { this.first.reset(); this.last.reset(); }
  clearInputMethod2() { this.form.setValue({first: '', last: ''}); }
  setValue() { this.form.setValue({first: 'Nancy', last: 'Drew'}); }
}

Try it out on stackblitz Clearing input in a FormGroup

Community
  • 1
  • 1
Aditya Vikas Devarapalli
  • 3,186
  • 2
  • 36
  • 54
  • Hi, in my case I'm using a `[formGroup]` and `formControlName` for send data to my Backend, but, I can't use `[(ngModel)]` or binding with `[Value]`. And trying to use `ElementRef` works fine but only with one `input` in my DOM, do you know another option to make that I'm looking for? – jecorrales Aug 17 '18 at 20:16
  • @jecorrales I've edited the answer to include your use-case. – Aditya Vikas Devarapalli Aug 20 '18 at 14:28
12

Method 1.

Using `ngModel`.

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

Plunker code: Plunker1

Method 2.

Using null value instead of empty quotation marks.

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

Plunker code: Plunker2

kind user
  • 40,029
  • 7
  • 67
  • 77
6

This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

  clear() {
    this.myForm.get('someControlName').reset()
  }
johannesMatevosyan
  • 1,974
  • 2
  • 30
  • 40
3

What about something like this, without a button:

<input type="text" placeholder="Search..." [value]="searchValue" onblur="this.value=''">
SirOnks
  • 31
  • 2
1

HTML

<input type="text" [(ngModel)]="obj.mobile" name="mobile" id="mobile" class="form-control" placeholder="Mobile/E-mail" />

TS

onClickClear(){
   this.obj.mobile= undefined;
}
Anand
  • 11
  • 5
0

Template driven method

#receiverInput="ngModel" (blur)="receiverInput.control.setValue('')"
wutzebaer
  • 14,365
  • 19
  • 99
  • 170
0

Some of the answers have suggested to do the following

this.myForm.get('fieldName').reset();

While that works fine, I personally like accessing the field object directly, instead of doing a string-based lookup.

this.myForm.controls.fieldName.reset();
James Poulose
  • 3,569
  • 2
  • 34
  • 39
0

With reactive forms in Angular with Ionic:

In library.page.html:

<ion-input type="text" placeholder="Search" [formControl]="searchControl"></ion-input>
<ion-icon name="close-circle" (click)="clearSearchInput()"></ion-icon>

In library.page.ts:

clearSearchInput() {
  this.searchControl.patchValue(false);
}
Stef Van Looveren
  • 302
  • 1
  • 5
  • 15