I am using Angular 6 to build an application. In my application I have the following code:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
constructor(private http: HttpClient) {}
setBackgroundImage(){
//code here..
}
searchCard(evt) {
evt.preventDefault();
let inputField_Id = <HTMLInputElement>document.getElementById("inputField_Id");
let id = inputField_Id.value;
//code here..
if(id){
let url = "http://localhost:3000/card/" + id;
this.sendToServer(url); //This is where the problem is
}
}
sendToServer(url){
this.http.get(url).subscribe(response => {
//code here..
});
}
ngOnInit() {
this.setBackgroundImage();
let searchForm = document.getElementById("searchForm");
searchForm.addEventListener("submit", this.searchCard);
}
}
I am trying to call the method/function sendToServer
from within the function searchCard
, but I can't manage to do it.
It tells me that "this.sendToServer is not a function at ..."
If I console.log(this);
within searchCard
I get the HTMLform-element which triggers the submit event.
If I created a let self = this;
variable within the function I get the same results.
Instead I tried creating self as a property of the class SearchComponent
, and setting self = this;
from within the ngOnInit
function. But then self == the window object. I tried the same thing from within the constructor, but with the same results.
How can I call sendToServer from within searchCard?