【问题标题】:Angular 4 - resetting a Reactive FormAngular 4 - 重置反应形式
【发布时间】:2017-12-15 22:31:59
【问题描述】:

使用响应式表单,我创建了一些控件

 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 重置表单。但是,我还需要恢复默认值。恢复“city”的默认值很容易,因为它只是一个表单控件。但是,如何重置“结构”(即 FormGroup)中 3 个复选框的值?

【问题讨论】:

    标签: angular


    【解决方案1】:
    '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,
     });     
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-15
      • 2018-01-16
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2018-11-30
      • 2018-06-16
      • 2018-09-22
      相关资源
      最近更新 更多