codependent codependent - 5 months ago 278
Javascript Question

Angular 2 - How to clear an input with a local variable

Following the guide fron the Angular2 site I have this html:

<input #something (keyup)="doneTyping($event)">
<button (click)="add(something .value)">Add</button>


with this controller:

@Component({
selector: 'my-app',
appInjector: [SomeService]
})
@View({
templateUrl: 'index-angular',
directives:[NgFor]
})
class MyAppComponent {
name: string;
stuff: Array<string>;

constructor(someService: SomeService) {
this.name = 'Angular2Sample';
this.stuff= someService.getStuff();
}
add(st: string){
this.stuff.push(st);
}
doneTyping($event) {
if($event.which === 13) {
this.stuff.push($event.target.value);
$event.target.value = null;
}
}
}


When the user hits enter in the input, the doneTyping method clears the input with
$event.target.value = null;
.

However I can't come with a way of doing the same after pushing the button.

Answer

You can pass the input as a parameter in the button

<input #something (keyup)="doneTyping($event)">

<!-- Input as paramter -->
<button (click)="add(something)">Add</button>

And later in the add function

add(st: HTMLInputElement){
    this.stuff.push(st.value);
    st.value = null;
  }