无法获得反应形式的只读文本框的值

问题描述:

我有一个read-only text input (3)如下所示。无法获得反应形式的只读文本框的值

enter image description here

.TS

wokeUpTime: number = 0; 

constructor(public formBuilder: FormBuilder,) { 
    this.sleepingDetailsForm = formBuilder.group({ 
     wokeUpTime: [0], 
    }); 
    } 

save(data): void { 
    if (this.sleepingDetailsForm.valid) { 
    //save 
} 
} 

的.html

<form [formGroup]="sleepingDetailsForm" (submit)="save(sleepingDetailsForm)" novalidate> 
    <h3 color="primary">Woke up time?</h3> 
    <div class="wokeuptime"> 
     <button type="button" (click)="decreaseWokeupTime()">-</button> 
     <input type="text" [readonly]="true" value={{wokeUpTime}} formControlName="wokeUpTime"> 
     <button type="button" (click)="increaseWokeupTime()">+</button> 
    </div> 
<button ion-button block type="submit" [disabled]="!sleepingDetailsForm.valid">Save</button> 

的问题在这里,我无法通过wokeUpTime得到只读文本输入的值。我在这里使用反应式的方法。我知道这是h由于我没有在文本框中输入任何内容,所以出现了这种情况。但是,对此的解决方法是什么?我需要通过表单变量this.sleepingDetailsForm获取值。我该怎么做?我知道我可以直接从save()方法中的this.wokeUpTime得到值,因为它是一个全局变量。但是我怎样才能从form本身得到它呢?

+0

请在下面创建一个生动的例子:www.plnkr.co – Marian07

+1

我编辑了我的帖子,万一你错过了它......使用单向绑定,如果你正在增加和减少'wokeUpTime' :) – Alex

编辑:甚至更​​好,如果你与wokeUpTime工作,你可以使用单向结合,并在窗体控件将获得价值组:

<input type="text" [ngModel]="wokeUpTime" [readonly]="true" 
     formControlName="wokeUpTime"> 

ORIGINAL POST:

但是,如果您增加或减少,则需要将值设置为表单控件。

所以它应该是:

this.sleepingDetailsForm.get('wokeUpTime').patchValue(...the new value here...) 

那么你的价值会的形式价值的一部分。

+0

非常好,非常感谢你,朋友:) – Sampath

+1

没问题,很高兴能帮到你!祝你有美好的一天和haaaaappy编码! :) – Alex

如果您使用的是反应形式,则不应该试图绑定value。您可以使用this.sleepingDetailsForm.value从您的代码中获得表单组的当前状态 - 因此,获取字段的值与this.sleepingDetailsForm.value.wokeUpTime一样简单。

+0

No.I have删除了值并尝试了这一行为。这是由于我没有在文本框中输入任何内容。如果我在其上键入内容,那么它很好地工作。这是什么解决方法?当用户增加/减少值时,我需要动态显示这个值。 – Sampath

+0

@Sampath,你为什么不使用? – Marian07