簡體   English   中英

函數內的Angular 2 ngModel

[英]Angular 2 ngModel inside a function

我正在嘗試將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

由於您有表單,我建議您完全跳過ngModels並使用您擁有的表單。 仍然有點不確定this.clientAction.transformInput(input)應該做什么,如你所解釋的那樣以某種方式轉換值。 你應該能夠在提交表格時加入這個內容嗎? 無論如何,如上所述,您將表單值安全地存儲在表單創建的對象中,您可能會看到以下內容:

{
  "monday":null,
  "tuesday":null,
  "wednesday":null,
  // ... and so on
}

當您鍵入字段時,您可以使用valueChanges捕獲每個按鍵,您可以在其中訪問完整的表單:

this.myForm.valueChanges.subscribe(res => {
  console.log("all form values: ", res) // here is an object with all your form values
})

如果需要,您還可以訪問每個表單控件,這里訪問星期一:

  console.log(this.myForm.controls['monday'].value) 

因此,這可以擺脫為每個表單值使用ngModel的麻煩。

所以這些有兩種方法可以攔截這些值,然后在你想要/需要的時候“轉換”它們。 可能最好的地方就是提交表單,循環值並轉換它們。 這是完全動態的,正如您所希望的那樣,並且不需要7個函數來轉換每個表單控件! ;)

希望這會對你有所幫助,而且這里有一個笨蛋(也請檢查控制台)。

Plunker

當您使用ngModel時,為什么要將相同的函數傳遞給函數

<ion-input text-right
               formControlName="monday"
               type="number" pattern="[0-9]*"
               placeholder="00.00"
               [(ngModel)]="monday"
               (keypress)="onChange()">
           </ion-input>

並使用ngModel本身處理

onChange(){
    input = this.clientAction.transformInput(this.monday);
}

更新1:

我讓你正在尋找變換文本框值的用戶輸入。 檢查自定義指令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM