[英]Bind object to input field in Ionic 2
I am stuck with a rather basic question but don't know how to google it. 我陷入一个相当基本的问题,但不知道如何使用谷歌搜索。
In my Ionic 2 app I have a AddPassengerPage with inout fields for name, email and phone. 在我的Ionic 2应用程序中,我有一个AddPassengerPage,其中包含用于姓名,电子邮件和电话的inout字段。 In my module I declare those variables: 在我的模块中,我声明了这些变量:
name: string;
phone: string;
email: string;
So in my view I can bind the input field to it: 所以在我看来,我可以将输入字段绑定到它:
<ion-input type="text" [(ngModel)]="email"></ion-input>
Later I want to pass the passenger to a provider which sends it to my API. 稍后,我想将乘客传递给提供者,该提供者将其发送到我的API。 What I would like to do is simply not have three variables but instead on passenger object, so my code would look like this: 我想做的只是没有三个变量,而是在乘客对象上,因此我的代码如下所示:
passenger: object;
And in my view: 在我看来:
<ion-input type="text" [(ngModel)]="passenger.email"></ion-input>
This is phantom code the way I wish it was. 这是我希望的幻影代码。 How would this look in real code? 这在真实代码中看起来如何?
I would suggest using an interface like so 我建议使用这样的界面
// This can be placed before 'export class AddPassengerPage'
// and after your import statements
interface Passenger {
name: string;
phone: string;
email: string;
}
// passenger can then be type checked against the defined interface of Passenger
passenger: Passenger;
Which will allow you to access the properties of the object using the dot notation. 这将允许您使用点符号访问对象的属性。
<ion-input type="text" [(ngModel)]="passenger.email"></ion-input>
Another option is to access the properties of a generic object using the square bracket operators. 另一种选择是使用方括号运算符访问通用对象的属性。
<ion-input type="text" [(ngModel)]="passenger['email']"></ion-input>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.