1

I'm using VS Code and I'm getting warnings in my code. I suppose I'm doing something wrong however the application is working as expected

<div class="search-wrapper">
  <input
    (keyup)="onKeyup($event)"
    type="search"
    id="searchInput"
    placeholder="Search..."
  />
  <button class="icon" (click)="clear()"><i class="fa fa-times"></i></button>
</div>

import { Component, OnInit } from "@angular/core";
import { SearchService } from "../services/search.service";

@Component({
  selector: "app-search",
  templateUrl: "./search.component.html",
  styleUrls: ["./search.component.scss"]
})
export class SearchComponent implements OnInit {
  constructor(private fs: SearchService) {}

  ngOnInit() {}

  onKeyup(event) {
    this.fs.updateFilter(searchInput.value);
  }

  clear() {
    this.fs.updateFilter("");
    searchInput.value = "";
  }
}

Problem is with reading value from input tag. As you can see in the code I'm just using the id to get access to the data but VS Code is showing me a warning that Cannot find searchInput. The code is working fine but since I'm getting the warning I assume I'm doing something wrong.

wojtekj
  • 55
  • 7
  • 1
    Setting aside Angular for a moment, you would grab an event target's value via `event.target.value`. That being said, if you can should manipulate the input's value either through binding with `ngModel` or via FormGroup/FormControl methods if it's a Reactive Form. At a basic level, `searchInput` is not a property that exists on the `SearchComponent` class or in the scope of `clear()` as a variable so you will always get that error as it simply does not exist in the current context. – Alexander Staroselsky Jan 31 '19 at 20:22
  • You're supposed to use Template Driven Forms or Reactive Forms to access data from any type of input. The warning that throw you is about the definition of the variable, because it isn't declared in any part of the component – Paulo Galdo Sandoval Jan 31 '19 at 20:22

1 Answers1

0

What is searchInput in your class ? If you think it's refers to id="searchInput" you wrong.

To access a DOM element from your class you should do what's described here: document.getElementById replacement in angular4 / typescript? .

Otherwise in onKeyup function, you can access to the value from the event by event.target.value.

Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50