首页 文章

Angular 4 - 重置反应表单

提问于
浏览
3

使用Reactive Forms,我创建了一些控件

ngOnInit() {
    this.myForm = new FormGroup({
      'name': new FormControl(null),
      'city': new FormControl('London'),
      'structure': new FormGroup({
        'Parallel': new FormControl('Parallel'),
        'Hierarchical': new FormControl('Hierarchical'),
        'Stable': new FormControl('Stable'),
      })
    })
}

'name'和'city'呈现为文本字段(城市具有默认值),'structure'呈现为复选框(全部选中) .

现在,我需要提供一个选项,将表单重置为默认值 . 因此,单击“重置”按钮,我将执行以下代码

onReset() {
   //Leaving out 'name', as it does not have a default value
    this.myForm.reset({
      'city': 'London',
      'structure': ?????, //What should I do here
    });     
}

form.reset重置表单 . 但是,我还需要恢复默认值 . 恢复“城市”的默认值很简单,因为它只是一个表单控件 . 但是,如何重置'structure'(FormGroup)中3个复选框的值?

1 回答

  • 8
    'structure' is a key-value pair by itself:
     onReset() {
       //Leaving out 'name', as it does not have a default value
        this.myForm.reset({
          'city': 'London',
          'structure':{
            'Parallel': 1,
            'Hierarchical': 1,
            'Stable': 1,
     });     
    }
    

相关问题