【发布时间】:2017-09-04 13:31:07
【问题描述】:
我正在尝试将 ngModel 传递给函数并获取更改,
不知道怎么用。
这是我现在得到的:
<ion-input text-right
formControlName="monday"
type="number" pattern="[0-9]*"
placeholder="00.00"
[(ngModel)]="monday"
(keypress)="onChange(monday)">
</ion-input>
<ion-input text-right
formControlName="tuesday"
type="number" pattern="[0-9]*"
placeholder="00.00"
[(ngModel)]="tueasday"
(keypress)="onChange(tuesday)">
</ion-input>
....等等...
然后在我的 page.ts 我得到了
monday: string = '';
tuesday: string = '';
etc...
onChange(input: string){
//I want the input to correspond to my ngModel so it gets updated
input = this.clientAction.transformInput(input);
}
我不想做:
this.monday = this.clientAction.transformInput(input);
因为您可能认为我一周中的每一天都有,所以我不想每天都有这样的功能:
onChangeMonday(){};
onChangeTuesday(){};
我需要一些动态的东西。
我该如何解决这个问题?
提前致谢
[解决方案] @AJT_82
解决方案不是使用我的 ngModel 并尝试更新它,而是从表单访问控件。
在您的 page.html 中
<ion-input text-right
formControlName="monday"
type="number" pattern="[0-9]*"
placeholder="00.00"
[(ngModel)]="monday"
(keypress)="onChange(monday, 'monday')">
</ion-input>
然后在你的 page.ts 中
onChange(input: string, day: string){
this.rateForm.controls[day].setValue(this.clientAction.transformInput(input));
}
现在就像一个魅力! 感谢@AJT_82
【问题讨论】:
-
你必须分享更多代码,我不确定这里应该发生什么:
input = this.clientAction.transformInput(input); -
嗨,AJT_82,input 是变量的名称,但是因为我在星期一通过输入 = this.clientAction.transformInput(input); 传递了示例我希望它和 this.monday = this.clientAction.transformInput(input); 一样其中 input = monday 所以它将我的请求结果重新分配给值 monday 这是我的 ngModel 谢谢
-
我只是编辑我的问题以便更好地解释
-
好的,现在我明白了:) 但仍然不确定
input = this.clientAction.transformInput(input);应该做什么?您是否需要在某处使用它。您还将更改的值保存在 formControls 中,您也可以使用它们。不知道更改事件应该做什么,因此我问这是为了什么:) -
请求
this.clientAction.transformInput(input)返回一个格式化的字符串,我需要在 ngModel 中重新注入。输入在我的代码中不存在,因为我正在寻找如何将我的请求的返回连接到this.input,意思是this.day_of_the_week,它对应于我的脚本中的一个变量。为了更好地理解,如果我更改为this.monday = this.clientAction.transformInput(input);而不是input = this.clientAction.transformInput(input);,它将更改星期一的 ngModel,但我需要为每天创建 7 个函数,每次都重复相同的代码。
标签: javascript angular ionic-framework