【问题标题】:Toggle Angular checkbox with string values instead of boolean true/false使用字符串值而不是布尔值 true/false 切换 Angular 复选框
【发布时间】:2022-02-16 21:37:56
【问题描述】:

我必须在我的表单中创建三个复选框,当我选中/取消选中复选框时,它们的值需要切换为“optin”和“optout”(字符串)。此外,我还需要默认选中所有复选框以获取“optin”值。我想不出任何解决方案,任何帮助都将不胜感激:(因为我对 angular 还很陌生

这是我正在处理的代码

component.html

<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">
    <div class="form-group">

   <input type="checkbox" formControlName="optOutFlag1" id="privacy" aria-labelledby="check1">
   <label for="privacy" id="check1"> Checkbox 1</label><br><br>

   <input type="checkbox" formControlName="optOutFlag2" id="security" aria-labelledby="check2">
   <label for="security" id="check2"> Checkbox 2</label><br><br>

   <input type="checkbox" formControlName="optOutFlag3" id="consent" aria-labelledby="check3">
   <label for="consent" id="check3"> Checkbox 3</label><br><br>

   <button> Submit Preference </button>

</div>
</form>

component.ts 文件

optOutForm:FormGroup
this.optOutForm=this.fb.group({
    optOutFlag1:["optin",Validators.required],
    optOutFlag2:["optin",Validators.required],
    optOutFlag3:["optin",Validators.required]
});  

【问题讨论】:

  • stackoverflow.com/questions/59910767/…。那就是你使用 [ngModel]="if the value of the formControl is 'optin'" and (ngModelChange)="set the value of the formControl if $event==true 'optin' and if is false 'optout'
  • 非常感谢@Eliseo 和 frank 的帮助。我已经粘贴了我的有效解决方案:]

标签: javascript angular typescript checkbox angular-forms


【解决方案1】:

使用复选框,Angular 表单控件的值被绑定到“选中”状态(而不是“值”属性),所以它应该是 truefalse

此外,您正在混合使用响应式表单和模板驱动表单。您可能应该做其中之一。

模板驱动表单

如果您想使用模板驱动的表单,您可以像这样更改您的模板:

...
<form name="optOutForm" (ngSubmit)="onSubmit()" #f="ngForm">
   <div>
      <input type="checkbox" name="privacyOptIn" id="privacyOptIn" 
         [(ngModel)]="optIn.privacy" required>&nbsp;
      <label for="privacyOptIn">Privacy</label>
   </div>
   <div>
      <input type="checkbox" name="securityOptIn" id="securityOptIn"
         [(ngModel)]="optIn.security" required>&nbsp;
      <label for="securityOptIn">Security</label>
   </div>
   <div>
      <input type="checkbox" name="consentOptIn" id="consentOptIn"
         [(ngModel)]="optIn.consent" required>&nbsp;
      <label for="consentOptIn">Consent</label>
   </div>
   <button>Submit Preference</button>
</form>
...

让你的组件像这样。请注意,模型 optIn 的属性全部设置为 true,因此默认选中复选框。

export class MyComponent {
    optIn: {
        privacy: boolean;
        security: boolean;
        consent: boolean;
    } = {
        privacy: true,
        security: true,
        consent: true
    };

    onSubmit() {
        ...
    }
}

See Stackblitz example here.

反应形式

但是,如果您想使用响应式表单,您可以像这样更改您的模板:

<form [formGroup]="form" (ngSubmit)="onSubmit()">
   <div>
       <input type="checkbox" formControlName="privacyOptIn" id="privacyOptIn">&nbsp;
       <label for="privacy">Privacy</label>
   </div>
   <div>
       <input type="checkbox" formControlName="securityOptIn" id="securityOptIn">&nbsp;
       <label for="security">Security</label>
   </div>
   <div>
       <input type="checkbox" formControlName="consentOptIn" id="consentOptIn">&nbsp;
       <label for="consent">Consent</label>
   </div>
   <button>Submit Preference</button>
</form>

然后您可以像这样在组件中设置表单:

export class MyComponent implements OnInit {
    form: FormGroup;
    submitted = false;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit() {
        this.form = this.formBuilder.group({
            privacyOptIn: [true, Validators.required],
            securityOptIn: [true, Validators.required],
            consentOptIn: [true, Validators.required]
        });
    }

    // Convenience getter for easy access to form fields
    get f() { return this.form.controls; }

    onSubmit() {
        ...
    }
}

See Stackblitz example here.

更新

如果您希望您的组件返回/发出'optin''optout' 字符串,您可以在表单提交期间简单地在组件中引入一个新变量:

export class MyComponent {
    @Output() options = new EventEmitter<{
        privacy: string;
        security: string;
        consent: string;
    }>();
    ...

    onSubmit() {
        const emittedOptions = {
            privacy: this.optIn.privacy ? 'optin' : 'optout',
            security: this.optIn.security ? 'optin' : 'optout',
            consent: this.optIn.consent ? 'optin' : 'optout',
        }
        this.options.emit(emittedOptions);
    }

See it work here

【讨论】:

  • 感谢您的详细解释 :] 非常感谢。此外,在提交表单而不是获取 true/false 之后,我们如何将复选框值设置为字符串而不是布尔值,我真正需要的是“optin”用于检查状态和“选择退出”用于未检查状态
  • @blume0F,请查看我对答案的更新
  • 我们可以在 html 中更改组件中的值,而不是更改值。使用 console.log(this.optOutForm.value) 应该显示复选框的字符串值
【解决方案2】:

此解决方案基于solution link by Eliseo

复选框在选中/取消选中时将值切换为“optin”或“optout”,并在 .ts 文件中默认初始化为“optin”

component.html 文件

<form [formGroup]="optOutForm" (ngSubmit)="submitOptFormValue()">

   <div class="form-group">

   <div class="optClass">
           <input  type="checkbox" 
           [ngModel]="optOutForm.get('optOutFlag1')?.value==='optin'"
           (ngModelChange)="optOutForm.get('optOutFlag1').setValue($event?'optin':'optout')"  
           [ngModelOptions]="{standalone:true}" id="privacy">

           <label "for="privacy" id="check1">Checkbox 1</label>
  </div>

 <div class="optClass">
           <input  type="checkbox" 
           [ngModel]="optOutForm.get('optOutFlag2')?.value==='optin'"
           (ngModelChange)="optOutForm.get('optOutFlag2').setValue($event?'optin':'optout')"  
           [ngModelOptions]="{standalone:true}" id="security">

           <label "for="security" id="check1">Checkbox 2</label>
  </div>

 <div class="optClass">
           <input  type="checkbox" 
           [ngModel]="optOutForm.get('optOutFlag3')?.value==='optin'"
           (ngModelChange)="optOutForm.get('optOutFlag3').setValue($event?'optin':'optout')"  
           [ngModelOptions]="{standalone:true}" id="consent">

           <label "for="consent" id="check1">Checkbox 3</label>
  </div>
</div>
</form>

component.ts 文件

optOutForm:FormGroup

constructor(private fb:FormBuilder){}

ngOnInit(){
 this.optOutForm=this.fb.group({
    optOutFlag1:['optin',Validators.required],
    optOutFlag2:['optin',Validators.required],
    optOutFlag3:['optin',Validators.required]
   });
}

【讨论】:

  • 我发现这种方法使您的模板难以阅读。但如果它有效,并且这就是你想要做的,没问题。
猜你喜欢
  • 2011-04-27
  • 2017-08-04
  • 2018-03-10
  • 2017-08-11
  • 1970-01-01
  • 2018-09-15
  • 2014-08-20
  • 2011-12-28
  • 1970-01-01
相关资源
最近更新 更多