繁体   English   中英

如何在 angular 2 中以反应形式重置验证器?

[英]How to reset validators in reactive form in angular 2?

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

嗨,你可以试试这样吗

this.form.reset()

提交后可以同时使用这两种方法吗

this.form.updateValueAndValidity()

取自提交后在 Angular 2 中重置表单

>= 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 示例

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

@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 示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM