Ionic 2无法从类更新表单值

时间:2016-08-19 15:53:29

标签: typescript ionic2

我在尝试使用离子2更新表单字段时遇到困难,这是规范:

Cordova CLI: 6.3.1
Gulp version:  CLI version 3.9.1
Gulp local:   Local version 3.9.1
Ionic Framework Version: 2.0.0-beta.11
Ionic CLI Version: 2.0.0-beta.37
Ionic App Lib Version: 2.0.0-beta.20
Node Version: v4.4.7

这是迄今为止的代码:

      <form [formGroup]="blueForm" (ngSubmit)="onSubmit()">
            <ion-item [class.error]="!deviceName.valid && deviceName.touched">
                <ion-label floating>Device Name</ion-label>
                <ion-input type="text" value="" formControlName="deviceName"></ion-input>         
            </ion-item>
            <div *ngIf="deviceName.hasError('required') && deviceName.touched"
                class="error-box">* Device Name is required!</div>               
            <br/><br/> 
            <ion-grid>
                <button type="submit" class="custom-button" [disabled]="!blueForm.valid" block>Change Name</button>
            </ion-grid>
        </form>

我尝试使用此功能更新值:

(<Control>this.blueForm.controls['deviceName']).updateValue('THE NEW VALUE', { onlySelf: true });

这里是表单定义:

    blueForm: FormGroup;

    deviceName = new FormControl("", Validators.required);

    constructor(private platform: Platform, public navCtrl: NavController, private fb: FormBuilder, private ref: ChangeDetectorRef) {
        this.blueForm = fb.group({
            "deviceName": this.deviceName,
        });
    }

最后错误是:

  

错误TS2352:既没有'AbstractControl'类型也没有输入'Control'   可转让给对方。类型中缺少属性“updateValue”   'AbstractControl'。

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容更新单个表单字段值。

this.blueForm.controls [' name ']。 patchValue (' new value '); this.blueForm.controls [' name ']。 setValue (' new value ');

有关详细说明,请查看此链接https://toddmotto.com/angular-2-form-controls-patch-value-set-value

答案 1 :(得分:0)

我认为问题是因为控件名为deviceName,但您尝试通过(<Control>this.blueForm.controls['name'])设置其值(请注意deviceName!= name)

另外,请尝试使用updateValueAndValidity(newValue)代替updateValue方法。