codependent codependent - 10 months ago 969
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:

selector: 'my-app',
appInjector: [SomeService]
templateUrl: 'index-angular',
class MyAppComponent {
name: string;
stuff: Array<string>;

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

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

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


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){
    st.value = null;