You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在表单中设置PrimeNG InputSwitch的预选中状态?

如何在表单中设置PrimeNG InputSwitch的预选中状态?

嗨,我来帮你搞定这个问题!当使用响应式表单(Reactive Forms)时,确实不能同时混用[(ngModel)]和formControlName,不过我们可以通过初始化表单控件的默认值来让InputSwitch默认处于选中状态,操作起来很简单,给你举个完整的示例:

第一步:模板代码(HTML)

<form [formGroup]="myForm">
  <p-inputSwitch formControlName="active"></p-inputSwitch>
  <!-- 可以加个按钮查看表单当前值 -->
  <button (click)="checkFormValue()">查看表单值</button>
</form>

第二步:组件类代码(TypeScript)

首先确保已经导入响应式表单的相关模块,然后在组件里初始化表单:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-input-switch-demo',
  templateUrl: './input-switch-demo.component.html'
})
export class InputSwitchDemoComponent implements OnInit {
  myForm!: FormGroup;

  ngOnInit(): void {
    // 初始化表单,给active控件设置默认值为true(实现默认选中)
    this.myForm = new FormGroup({
      active: new FormControl(true)
    });
  }

  checkFormValue(): void {
    console.log(this.myForm.value); // 查看表单的当前状态值
  }
}

如果你习惯用FormBuilder简化表单创建,代码会更简洁:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-input-switch-demo',
  templateUrl: './input-switch-demo.component.html'
})
export class InputSwitchDemoComponent implements OnInit {
  myForm!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.myForm = this.fb.group({
      active: [true] // 这里设置初始值为true,InputSwitch就会默认选中
    });
  }

  checkFormValue(): void {
    console.log(this.myForm.value);
  }
}

核心逻辑很简单:在创建表单控件时,把初始值设为true就能让InputSwitch默认选中;如果想要默认不选中,把初始值改成false就可以啦。

备注:内容来源于stack exchange,提问作者JBC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 14:47:32