【问题标题】:How to reset validators in reactive form in angular 2?如何在角度 2 中以反应形式重置验证器?
【发布时间】:2018-02-19 07:59:54
【问题描述】:

我使用了 angular Reactive from。但是当我在提交表单后重置表单时,验证器无效并显示无效的表单样式。 如何使验证器重置? 谁能帮我解决这个问题。

【问题讨论】:

标签: angular angular2-forms angular-forms


【解决方案1】:

你好,你可以这样试试

this.form.reset()

提交后两种方法都可以用吗

this.form.updateValueAndValidity()

【讨论】:

  • 它不会重置验证器。
  • 我用的是素材输入框。
  • 这在带有材料输入的反应形式中不起作用,它一直以红色显示刚刚清除或重置的字段
  • @Robert 好吧,我不是 OP,我已经尝试过这个答案,并且在使用它重置后仍然以红色显示所需的输入
【解决方案2】:

取自Resetting a form in Angular 2 after submit

>= RC.6

支持重置表单并保持submitted 状态。

console.log(this.form.submitted);
this.form.reset()

this.form = new FormGroup()...;

重要更新

要在创建表单时将表单控件设置为某种状态,例如验证器,需要进行一些额外的测量

在表单的视图部分 (html) 添加*ngIf 以显示或隐藏表单

<form *ngIf="showForm"

在表单的组件端 (*.ts) 执行此操作

  showForm:boolean = true;

  onSubmit(value:any):void {
    this.showForm = false;
    setTimeout(() => {
    this.reset()
      this.showForm = true;
    });
  }

这里有一个更详细的例子:

export class CreateParkingComponent implements OnInit {
  createParkingForm: FormGroup ;
  showForm = true ;

  constructor(
    private formBuilder: FormBuilder,
    private parkingService: ParkingService,
    private snackBar: MatSnackBar) {

      this.prepareForm() ;
  }

  prepareForm() {
    this.createParkingForm = this.formBuilder.group({
      'name': ['', Validators.compose([Validators.required, Validators.minLength(5)])],
      'company': ['', Validators.minLength(5)],
      'city': ['', Validators.required],
      'address': ['', Validators.compose([Validators.required, Validators.minLength(10)])],
      'latitude': [''],
      'longitude': [''],
      'phone': ['', Validators.compose([Validators.required, Validators.minLength(7)])],
      'pictureUrl': [''],
      // process the 3 input values of the maxCapacity'
      'pricingText': ['', Validators.compose([Validators.required, Validators.minLength(10)])],
      'ceilingType': ['', Validators.required],
    });
  }

  ngOnInit() {
  }


  resetForm(form: FormGroup) {
    this.prepareForm();
  }

  createParkingSubmit() {
    // Hide the form while the submit is done
    this.showForm = false ;

    // In this case call the backend and react to the success or fail answer

    this.parkingService.create(p).subscribe(
      response => {
        console.log(response);
        this.snackBar.open('Parqueadero creado', 'X', {duration: 3000});
        setTimeout(() => {
          //reset the form and show it again
          this.prepareForm();
            this.showForm = true;
          });
      }
      , error => {
        console.log(error);
        this.showForm = true ;
        this.snackBar.open('ERROR: al crear Parqueadero:' + error.message);
      }
      );
  }
}

Plunker example

原版 只需将创建表单的代码移动到一个方法中,并在处理完提交后再次调用它:

@Component({
  selector: 'form-component',
  template: `
    <form (ngSubmit)="onSubmit($event)" [ngFormModel]="form">
       <input type="test" ngControl="name">
       <input type="test" ngControl="email">
       <input type="test" ngControl="username">
       <button type="submit">submit</button>
    </form>
    <div>name: {{name.value}}</div>
    <div>email: {{email.value}}</div>
    <div>username: {{username.value}}</div>
`
})
class FormComponent {

  name:Control;
  username:Control;
  email:Control;

  form:ControlGroup;

  constructor(private builder:FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.name = new Control('', Validators.required);
    this.email = new Control('', Validators.required);
    this.username = new Control('', Validators.required);

    this.form = this.builder.group({
      name: this.name,
      email: this.email,
      username: this.username
    });
  }

  onSubmit(value:any):void {
    // code that happens when form is submitted
    // then reset the form
    this.reset();
  }

  reset() {
    this.createForm();
  }
}

Plunker example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 2018-12-28
    • 2021-10-02
    • 2020-01-27
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多