angular - 如何在 Angular 中一起使用 *ngIf 和条件要求?

标签 angular

<div class="p-field-checkbox">
    <p-checkbox formControlName="passwordUpdate" binary="false" name="passwordUpdate" inputId="passwordUpdate"></p-checkbox>
    <label for="passwordUpdate">Update Password</label>
</div>

<div class="input-group" *ngIf="form.get('passwordUpdate').value">
    <label class="required" for="password">Password</label>
    <input formControlName="password" type="password" name="password" placeholder="Password" id="password" class="input input-m" [required]="form.get('passwordUpdate').value">
</div>

如果条件为“true”,则会出现密码字段。单击提交按钮后,将验证密码字段是否为必填字段。

然后条件变为“假”,但所需的验证未删除,因此无法提交表单。请帮我解决这个问题。提前致谢。

最佳答案

当您使用 ReactiveForms 时,我们可以根据“passwordUpdate”的状态添加和删除验证

<form [formGroup]="contactForm">
  <div>
    <label>Update Password</label>
    <input type="checkbox" formControlName="resetPassword" (change)="onCheckboxChange()" />
  </div>
  <div *ngIf="contactForm.get('resetPassword')?.value">
    <label for="last-name">Password: </label>
    <input type="text" formControlName="password">
    Required: {{ contactForm.get('password')?.hasError('required') }}
  </div>
  <div>
    <button type="submit">Submit</button>
    Valid Form : {{ contactForm.valid }}
  </div>
</form>

我添加了“更改”函数,该函数会触发 .ts 文件中的一个函数,该函数会重置“密码”字段的验证。

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  contactForm!: FormGroup;
  constructor(private formBuilder: FormBuilder) {
    this.createContactForm();
  }

  createContactForm() {
    this.contactForm = this.formBuilder.group({
      resetPassword: [],
      password: [],
    });
  }

  onCheckboxChange(): void {
    if (this.contactForm.controls['resetPassword'].value) {
      this.contactForm.get('password')?.setValidators([Validators.required]);
      this.contactForm.get('password')?.updateValueAndValidity();
    } else {
      this.contactForm.controls['password'].clearValidators();
      this.contactForm.get('password')?.updateValueAndValidity();
    }
  }
}

我在 stackblitz 上创建了一个相同的模拟项目。请检查以供引用。

关于angular - 如何在 Angular 中一起使用 *ngIf 和条件要求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69466441/

相关文章:

javascript - 如何在 Angular 上向 react 形式添加特定验证

java - 如何向所有人开放端点?

javascript - 保留 HTML 到文本区域的格式

Angular 2.0.0 Metadata_resolver 奇怪的行为

angular - 在 Angular + Jest 中运行单元测试时如何正确模拟库 "Twemoji"?

forms - 输入类型编号 "only numeric value"验证

angular - 如何在 Angular 6 中实现延迟组件投影?

angular - 无法读取未定义的属性 'create'

javascript - 以 Angular 计算子对象中变量的出现次数

Angular - JWT 刷新 token