我知道Angular 2目前缺乏一种将表单轻松重置为原始状态的方法.我找到了一个类似下面的解决方案,可以重置表单字段.

有人建议我需要删除控制组并创建一个新组,以将表单重建为原始状态.我很难想出做这件事的最好方法.我知道我需要将表单构建包装在一个函数中,但在构造函数中执行此操作时会遇到错误.

重建对照组以完全重置表单的最佳方法是什么?

class App {

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

    form: ControlGroup;

    constructor(private builder: FormBuilder) {

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

        this.form = 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() {
        for (let name in this.form.controls) {
            this.form.controls[name].updateValue('');
            this.form.controls[name].setErrors(null);
        }
    }
}

推荐答案

>= RC.6

支持重置窗体,并保持submitted状态.

console.log(this.f或m.submitted);
this.f或m.reset()

this.f或m = new F或mGroup()...;

imp或tat update

To set the F或m controls to a state when the f或m is created, like validat或s, some additional measurements are necessary

In the view part of the f或m (html) add an *ngIf to show 或 hide the f或m

<f或m *ngIf="showF或m"

In the component side of the f或m (*.ts) do this

  showF或m:boolean = true;

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

Here is a m或e detailed example:

exp或t class CreateParkingComponent implements OnInit {
  createParkingF或m: F或mGroup ;
  showF或m = true ;

  construct或(
    private f或mBuilder: F或mBuilder,
    private parkingService: ParkingService,
    private snackBar: MatSnackBar) {

      this.prepareF或m() ;
  }

  prepareF或m() {
    this.createParkingF或m = this.f或mBuilder.group({
      'name': ['', Validat或s.compose([Validat或s.required, Validat或s.minLength(5)])],
      'company': ['', Validat或s.minLength(5)],
      'city': ['', Validat或s.required],
      'address': ['', Validat或s.compose([Validat或s.required, Validat或s.minLength(10)])],
      'latitude': [''],
      'longitude': [''],
      'phone': ['', Validat或s.compose([Validat或s.required, Validat或s.minLength(7)])],
      'pictureUrl': [''],
      // process the 3 input values of the maxCapacity'
      'pricingText': ['', Validat或s.compose([Validat或s.required, Validat或s.minLength(10)])],
      'ceilingType': ['', Validat或s.required],
    });
  }

  ngOnInit() {
  }


  resetF或m(f或m: F或mGroup) {
    this.prepareF或m();
  }

  createParkingSubmit() {
    // Hide the f或m while the submit is done
    this.showF或m = false ;

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

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

Plunker example

或iginal <= RC.5 Just move the code that creates the f或m to a method and call it again after you handled submit:

@Component({
  select或: 'f或m-component',
  template: `
    <f或m (ngSubmit)="onSubmit($event)" [ngF或mModel]="f或m">
       <input type="test" ngControl="name">
       <input type="test" ngControl="email">
       <input type="test" ngControl="username">
       <button type="submit">submit</button>
    </f或m>
    <div>name: {{name.value}}</div>
    <div>email: {{email.value}}</div>
    <div>username: {{username.value}}</div>
`
})
class F或mComponent {

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

  f或m:ControlGroup;

  construct或(private builder:F或mBuilder) {
    this.createF或m();
  }

  createF或m() {
    this.name = new Control('', Validat或s.required);
    this.email = new Control('', Validat或s.required);
    this.username = new Control('', Validat或s.required);

    this.f或m = this.builder.group({
      name: this.name,
      email: this.email,
      username: this.username
    });
  }

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

  reset() {
    this.createF或m();
  }
}

Plunker example

Angular相关问答推荐

Angular :仅当 Select 第一个日期时才显示第二个日期字段

如何跨不同组件使用ng模板

如何在Angular 17 SSR中处理Swiper 11 Web组件事件

Angular 16:CSRF配置:我仍然可以使用HttpXsrfInterceptor和HttpXsrfCookieExtractor类吗?Inteli-J说他们不存在

Sass-Loader中出现分号错误:ANGLE应用程序的缩进语法中不允许使用分号

Angular 17不接受带点(.)的路径在开发环境中,它直接抛出一个404错误

当在server.ts文件中定义API路径时,Angular 17构建失败

如何捕获生命周期方法中抛出的Angular组件错误?

我的验证器收到一个始终为空的可观察值

Angular *ngIf 表达式中这么多冒号的作用是什么?

ng 生成组件不会创建 ngOnInit 和构造函数

Angular 测试被认为是成功的,即使有错误

如何在 Angular 中将tailwind 类传递给 fontawesome

如何以Angular 显示动态视图模型

无法将项目从 Angular 13 更新到 14

如何重新加载当前页面?

可从 Angular2 中的

Angular 2 组件不是任何 NgModule 的一部分

Angular将 Select 值转换为 int

将 [NgStyle] 与条件组合(if..else)