SP de Wit SP de Wit - 4 months ago 14
Javascript Question

Sending form input to a method in Angular 2

I've made the following Angular 2 application witch makes use of the numbers API. I would like the user to input a day of the month and a month of the year and when they click the button that data should be sent to the getDayEvent() method which then initiates the service(which works using dummy data). I just need to find a way to send the form data to the method. I've done some research on formcontrols and formgroups but I'm struggling to implement it in my application.

@Component({
selector: 'http-test',
template:
`
<br>
<form id="myForm" >
<table>
<tr>
<td><label>Enter a month</label></td>
<td><input type="text" ></td>
</tr>
<tr>
<td><label>Enter a day</label></td>
<td><input type="text"></td>
</tr>
<tr>
<td><button type="submit">See what happened on this day</button>
</td>
</tr>
</table>
</form>
<br>
<p id="output">{{event}}</p>
`,
providers: [HttpService],
directives: [CORE_DIRECTIVES, FORM_DIRECTIVES]
})

export class HttpComponent {
event: string;


constructor(private _httpService: HttpService){

}

getDayEvent(month:string, day:string){
this._httpService.getEvent(month, day)
.subscribe(
data => this.event = JSON.stringify(data),
error => alert(error),
() => console.log("Finished")
);
}
}


And here is my service

@Injectable()
export class HttpService{
constructor(private _http: Http){}

getEvent(month: string, day: string){
return
this._http.get('http://numbersapi.com/'+month+'/'+day+'/date').map(res
=> res.text());
}
}

Answer

You could use ngModel in your inputs and click event in your button.

template inputs and button:

<input [(ngModel)]="month" type="text">
<input [(ngModel)]="day" type="text">
<button type="submit" (click)="getDayEvent(month,day)">See what happened on this day</button>

add the member variables to your class:

export class HttpComponent {
event: string;
month: string;
day:string;