将表单输入发送到 Angular 2 中的方法
Sending form input to a method in Angular 2
我做了以下 Angular 2 应用程序 使用了数字 API。我希望用户输入一个月中的一天和一年中的一个月,当他们单击按钮时,数据应该发送到 getDayEvent() 方法,然后启动服务(使用虚拟数据工作)。我只需要找到一种方法将表单数据发送到方法。我对 formcontrols 和 formgroups 做了一些研究,但我很难在我的应用程序中实现它。
@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")
);
}
}
这是我的服务
@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());
}
}
您可以在输入中使用 ngModel 并在按钮中使用点击事件。
模板输入和按钮:
<input [(ngModel)]="month" type="text">
<input [(ngModel)]="day" type="text">
<button type="submit" (click)="getDayEvent(month,day)">See what happened on this day</button>
将成员变量添加到您的 class:
export class HttpComponent {
event: string;
month: string;
day:string;
我做了以下 Angular 2 应用程序 使用了数字 API。我希望用户输入一个月中的一天和一年中的一个月,当他们单击按钮时,数据应该发送到 getDayEvent() 方法,然后启动服务(使用虚拟数据工作)。我只需要找到一种方法将表单数据发送到方法。我对 formcontrols 和 formgroups 做了一些研究,但我很难在我的应用程序中实现它。
@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")
);
}
}
这是我的服务
@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());
}
}
您可以在输入中使用 ngModel 并在按钮中使用点击事件。
模板输入和按钮:
<input [(ngModel)]="month" type="text">
<input [(ngModel)]="day" type="text">
<button type="submit" (click)="getDayEvent(month,day)">See what happened on this day</button>
将成员变量添加到您的 class:
export class HttpComponent {
event: string;
month: string;
day:string;