【问题标题】:Ionic2 checkbox with formControlName带有 formControlName 的 Ionic2 复选框
【发布时间】:2019-05-25 05:05:13
【问题描述】:

实际上我在 ionic2 中使用复选框时遇到了一个问题。

我将复选框用作:

<ion-item>
    <ion-label>Agree</ion-label>
    <ion-checkbox color="dark" id="agree" name='agree' class="form-control" formControlName="agree" [checked]="false" ></ion-checkbox>
  </ion-item>

在 .ts 中,我将其值获取为:

console.log(this.timelogForm.controls['agree'].value);

我希望最初不选中它。

我的问题是:

  1. 在使用 formControlName="agree" 时会检查 ..

  2. 如果它被点击一次,我会在 .ts 中获得它的值,但如果没有点击提交,我会得到 false,如果选中,我会得到 true..

请帮忙

【问题讨论】:

  • 通过从ion-checkbox 中删除属性[checked]="false" 进行检查
  • 我删除了它,但同样有两个问题:默认情况下它被选中,我必须单击它一次才能获得它的值,但我希望它不被选中。

标签: angular typescript ionic2


【解决方案1】:

我自己解决了,希望对某人有所帮助..

我将其值设置为 false,例如:

this.logForm = formBuilder.group({
        'agree': ['false'],
    });

希望对某人有所帮助。

【讨论】:

    【解决方案2】:

    test.ts

    buildForm(){
        this.accountForm = this.formBuilder.group({
            generalTerms: ['', Validators.requiredTrue]
        });
    }
    

    test.html

    <form [formGroup]="accountForm">
        <ion-item class="center">
            <ion-checkbox formControlName="generalTerms" checked="false"></ion-checkbox>
            <ion-label>Accepter les conditions générale</ion-label>
        </ion-item>
        <ion-item class="button" lines="none">
            <ion-button color="primary [disabled]="accountForm.invalid" 
            (click)="save()">
            Valider
            </ion-button>
        </ion-item>
    </form>
    

    【讨论】:

    • 解释你的代码的一些词会让你的答案更有用
    • generalTerms: ['false', Validators.requiredTrue]内将默认值设置为false,而不是将ion-checkbox上的checked属性设置为false
    【解决方案3】:

    它的工作。希望对你有帮助。

    test.ts

    import { Component } from '@angular/core';
    import { NavController, Events } from 'ionic-angular';
    import { FormGroup, FormBuilder, Validators } from '@angular/forms';
    @Component({
        templateUrl: 'test.html'
    })
    export class test implements OnInit {
        logform: FormGroup;
        forgotPasswordEmail: any;
        constructor(private _navCtrl: NavController, private _fb: FormBuilder) { }
        ngOnInit() {
            this.logform = this._fb.group({
                ckeckbox: ['false', Validators.required]
            });
        }
    }
    

    test.html

    <ion-item>
        <ion-label>Daenerys Targaryen</ion-label>
        <ion-checkbox color="dark" formControlName="ckeckbox" checked="false"></ion-checkbox>
    </ion-item>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-27
      • 2018-01-15
      • 2020-03-24
      • 1970-01-01
      • 2017-05-12
      • 2017-10-04
      • 1970-01-01
      • 2013-06-19
      相关资源
      最近更新 更多