【问题标题】:Sending form input to a method in Angular 2将表单输入发送到Angular 2中的方法
【发布时间】:2016-12-08 06:24:03
【问题描述】:

我使用 numbers API 制作了以下 Angular 2 应用程序。我希望用户输入一个月中的一天和一年中的一个月,当他们单击按钮时,数据应发送到 getDayEvent() 方法,然后该方法启动服务(使用虚拟数据工作)。我只需要找到一种将表单数据发送到方法的方法。我已经对表单控件和表单组进行了一些研究,但我正在努力在我的应用程序中实现它。

@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());
    }
    }

【问题讨论】:

    标签: javascript angularjs angular angular2-forms


    【解决方案1】:

    您可以在输入中使用 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>
    

    将成员变量添加到您的类中:

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

    【讨论】:

    • 感谢一百万!老实说,没想到会那么容易。非常感谢您的帮助,因为我对 Angular 2 还很陌生,所以我整天都在为此苦苦挣扎,现在我可以安息了。
    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2017-03-24
    • 1970-01-01
    • 2020-09-12
    • 2017-09-14
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多