Angular PrimeNG Inputswitch 显示段落

Angular PrimeNG Inputswitch show paragraph

我对这一切都很陌生。我只是想在选中 p-inputSwitch 时显示一个段落元素(选中后它会再次消失 again/false)。

这是我的HTML(组件):

  <p-inputSwitch formControlName="bonus" 
                 (onChange)="clickBonusChecked($event)" 
                 onLabel="yes" 
                 offLabel="no">
   </p-inputSwitch>

   <p *ngIf="bonusChecked === true">Paragraph I want shown</p>

这是我的 TS 组件:

export class Component implements OnInit {
  bonusChecked: boolean;

  constructor(){}

  public ngOnInit(): void {
   this.bonusChecked = false;
  }

  public clickBonusChecked(e) {
   const bonusChecked = e.checked;
    if (bonusChecked) {
      console.log('jsdhck');
    }
  }

有人知道如何进行这项工作吗?我发现 PrimeNG 文档非常有限..

只需使用[ngModel]

从域模型创建 FormControl 实例并将其绑定到表单控件元素。

并使用 *ngIf 显示和隐藏这样的段落 *ngIf="bonusChecked"

您可以像这样检查 p-inputSwitch 的状态

<h3 class="first">Basic - {{bonusChecked}}</h3>

HTML

<h3 class="first">Basic - {{bonusChecked}}</h3>


<p-inputSwitch [(ngModel)]="bonusChecked"
                 (onChange)="clickBonusChecked($event)" 
                 onLabel="yes" 
                 offLabel="no">
   </p-inputSwitch>

   <p *ngIf="bonusChecked">Paragraph I want shown</p>

TS

bonusChecked: boolean = false;

  constructor(){}

  public ngOnInit(): void {
   this.bonusChecked = false;
  }

  public clickBonusChecked(e) {
   const bonusChecked = e.checked;
    if (bonusChecked) {
      console.log('jsdhck');
      this.bonusChecked = true;
    }
 }

您可以编辑或预览Here on StackBlitz

您需要在 clickBonuesChecked 函数中设置 bonusChecked = true

this.bonusChecked = e.checked;

我假设 e.checked returns true 或 false 而不是不写 if 条件,因为我正在检查你只是将它用于 console.log

你需要用到这个。 现在你创建了一个全新的 var

   public clickBonusChecked(e) {
   this.bonusChecked = e.checked;
    if (bonusChecked) {
      console.log('jsdhck');
    }
  }

使用 [(ngModel)] 非常简单。这里是stackblitz

如果要响应式,需要订阅元素的变化事件

这里是stackblitz reactive form