【问题标题】:How to get the formgroup values and show all of them on parent component如何获取表单组值并将它们全部显示在父组件上
【发布时间】:2021-07-27 03:37:50
【问题描述】:

我有一个响应式表单,我正在将来自 db 的数据绑定到 ngOninit 上的表单上,并且还对表单控件和表单数组元素进行验证。

我有另一个表单,其中包含相同的信息以在提交之前进行审核,我可以使用 @Input() 将这些值绑定到不同的组件中。

我希望每当我更改表单内任何 formcontrol 或 formarray 上的任何内容时,它都应该反映在审阅表单上。

我曾尝试在 ngOnInit 中订阅 form 的 valueChange 事件,但每当我更改任何控件或 formarray 值时它都不会触发。


请帮助我如何使用 valueChange 来获取表单上的所有 formcontrols 和 formarray 值,每当我更新主表单上的任何内容时,都会在审核表单上更新。

【问题讨论】:

    标签: angular angular9 subscribe valuechangelistener


    【解决方案1】:

    你能展示你的一些代码或发布你项目的 jsFiddle 吗?

    如果我正确理解您的问题,这将是一个好方法:

    在html中

    <div [formGroup] = "formGroup">
    
        ... //all the other forms
    
        <mat-form-field>
            <input matInput type="number" formControlName="name" [(ngModel)] = "name">
        </mat-form-field>
    </div>
    

    在组件中:

    import { Component, OnInit, ElementRef, ViewChild, Inject } from '@angular/core';
    import { FormGroup, FormControl, Validators } from '@angular/forms';
    
    formGroup!: FormGroup;
    name!: number
    ... //all the other form properties
    
    @ViewChild('input') input!: ElementRef;
    
      ngOnInit(): void {
        this.formGroup = new FormGroup({
          sequenceId: new FormControl(null, [Validators.pattern('//pattern for validation')]),
        });
      }
    

    [(ngModel)] 将表单的值与组件的name 属性绑定,就像您在表单中编写的那样。

    我正在使用角度材料的&lt;mat-form-field&gt;matInput。即使使用普通形式,这也应该可以工作

    【讨论】:

    • Maurizio,请不要在同一标签中使用 formControlName[(ngModel)]。如果你想用一个值初始化 FormControl,你可以使用 new FormControl(this.name,[Validators....])
    • @Eliseo 我没有使用[(ngModel)] 用值初始化表单,我使用它来更新name 属性,因为表单值得到更新,我也使用的原因formControl 仅用于验证
    • 您可以在同一标签中使用 formControlName 和 [(ngModel)]。 NgModel 用于 Tempalte 驱动的表单,formControlName 用于响应式表单。如果你有一个 ReactiveForm,你有“formGroup.value”中的值。使用“如果你想改变 - 真的没有必要有两个变量给出相同的值。
    【解决方案2】:

    您能否尝试在 ngOnchange 生命周期方法中使用 valueChange 事件。如果您想将表单值传递给父组件,您可以使用 eventEmitter 或将 formData 作为行为主体 (RxJS) 并在每次更改时发布数据并在父组件中订阅表单数据。

    【讨论】:

    • 我可以将值传递给父表单,但是当我更改子表单上的任何内容时,它不会反映在父表单上。我相信我们必须订阅 valueChange 事件但是当我尝试使用它时 ngOninit 它没有工作。让我在 ngOnChange 上试一试。
    【解决方案3】:

    我可以通过在 oninit 的父页面上添加以下代码行来更改表单上的值。以前我在主窗体上使用它。

    @Input() 形式:任意; 类别:字符串;

    this.form.get("category").valueChanges.subscribe(value => { this.category = 价值;

    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 2016-06-25
      • 1970-01-01
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2020-11-25
      相关资源
      最近更新 更多