【问题标题】:how to get values on change event in dynamic angular forms?如何以动态角度形式获取更改事件的值?
【发布时间】:2018-09-04 05:36:37
【问题描述】:

在 component.ts 文件中,我正在像这样获取 json 数组中的表单字段值并将其转换为这样的 FormGroup 控件。这工作得很好。

    getJsonForm(){
      let base_url = 'example.org'
      let getform_query = '/Base/formfieldsgenerator_get';
      let getform_endpoint = base_url.concat(getform_query);

     this.AllFormData = [];

        this.http.get('getform_endpoint'.'?tabpgrpid='+this.tabpgrpid+'&tabgrpname='+this.tabgrpname+'&usertabgrpname='+this.usertabgrpname+'&moduleid='+this.moduleid+'&templateid='+this.templateid+'&all_mod_data='+this.all_mod_data,{headers: this.headers}).subscribe(
        res => { 
         this.AllFormData = res;

                // this array is used to iterate in html side
               this.newfdata[element] = [];
               this.newfdata[element]['properties'] = [];


   Object.keys(res['com'][element]['schema']['properties']).forEach(inputKey => {
                      this.newfdata[element]['properties'].push(res['com'][element]['schema']['properties'][inputKey]);

                });

            // this is used to create form controls and form groups

                this.objectProps = Object.keys(res['com'][element]['schema']['properties']).map(prop => { 

          return Object.assign({}, { key: prop} , res['com'][element]['schema']['properties'][prop]);
          });

   for(let prop of Object.keys(res['com'][element]['schema']['properties'])) {

          formGroup[prop] = new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));

                }
        });

      this.form = new FormGroup(formGroup);
          }); 
}

现在在 components.html 方面,我正在使用这样的数组来生成动态表单。这也工作正常。

<form (ngSubmit)="custom_submit(form.value)" [formGroup]="form" >
         <div *ngFor="let input1 of newfdata[tabname].properties">   
                <ng-container *ngIf="input1.type=='string'">
                                <div>
                                     <mat-form-field>
                                     <input matInput  [formControlName]="input1.field_name" [id]="input1.field_name" type="text"  placeholder="{{input1.title}}">
                                     </mat-form-field>   
                                </div>
                            </ng-container>
         </div>  
</form>

现在我想根据以前表单字段的更改来更改一个表单字段的值。为此,我无法订阅表单组变量的 valuechanges 发射器。

我已经在 ngOnit 上尝试过了,但它不起作用,并且在控制台中没有产生任何结果。

ngOnit(){

   this.form.valueChanges.subscribe(val => {
                    this.formattedMessage = 'My changed values for is ${val}.';
                    console.log(this.formattedMessage);
                  });



}

编辑 1:

根据 Manzur Khan 的建议,我将值作为 true 传递给 formcreated 事件,然后在 ngOnit 中使用这样的值来获取 onchange 事件:

      this.form = new FormGroup(formGroup);
      this.dataService.change_current_form_created("true");

在 NgonIt 中

this.dataService.last_form_craeted_message.subscribe(data => {
  if(data=="true") {
    this.form.valueChanges.subscribe(val => {
         this.formattedMessage = 'My changed values for is ${val}.';
            console.log(this.formattedMessage);
        });
}
});

现在我可以在控制台中登录更改事件,但无法获得 ${val} 的分辨率。

编辑 2:

由于 val 是对象,我无法以某种方式解析 ${val},我只是做了

   this.form.valueChanges.subscribe(val => {
            console.log('the changed value is',val);
        });

它为我提供了给定表单组的所有值。我仍然需要进一步优化这个结果,以便我只听特定的表单控件。但它给了我一条可以走的路。谢谢大家。

【问题讨论】:

  • 请将相关代码添加到您的查询中。由于额外的东西,它会混淆您的实际查询。
  • 不要把代码放在 ngOnInit 中,就在你的行之后:this.form = new FormGroup(formGroup)。好吧,为了清楚起见,创建一个函数并在该行之后调用它
  • “现在我想根据以前表单字段的更改来更改一个表单字段的值”。好吧,考虑一下该值是否必须属于表单。如果你的“field”formattedMessage是“My ChangeValue”+input1.value,你不能有这个“field”,只是一个{{“My change Value”+form.getControl('input1').value}}
  • @mayur :这是让您了解整个场景的实际代码片段。这里没有什么是多余的。

标签: angular typescript events angular-reactive-forms eventemitter


【解决方案1】:

发生这种情况是因为您甚至在表单出现之前就在监听表单的值变化(因为它在异步内部)

你可以试试这样的

首先声明一个 Observable

formCreated: Subject<boolean> = new Subject();

然后在你的表单代码中

this.form = new FormGroup(formGroup);
this.formCreated.next(true)

然后在你的 ngOnInit 中

this.formCreated.subscribe(data => {
  if(data) {
    this.form.valueChanges.subscribe(val => {
         this.formattedMessage = 'My changed values for is ${val}.';
            console.log(this.formattedMessage);
        });
}
})

【讨论】:

  • 当我这样做时。它给了我两个错误, ERROR TypeError: Cannot read property 'subscribe' of undefined at AddComponent.ngOnInit 和 Cannot read property 'next' of undefined at SafeSubscriber ,所以我需要在某处定义 this.formCreated 吗?如果是这样,怎么办?
  • @Manzur Khan,您无需创建已提交的表单。只是,在创建表单(是一个同步功能)之后,创建对 valueChanges 的订阅
  • @Eliseo ,我正在检查您的方法。
  • @Manzur Khan,我创建了一个公共共享服务,在这样创建表单后,它的值保持为真。 this.form = new FormGroup(formGroup); this.dataService.change_current_form_created("true"); this.dataService 是我用来将消息传递给差异的公共服务。成分。现在我可以在控制台中记录值更改事件,但只收到这样的消息,我更改的值是 ${val}。';而不是价值本身。
  • @Manzur Khan,请提供 Formcreated 的正确定义或声明,(在我的例子中,我创建了一个行为,可观察的主题)。这样我就可以将您的答案标记为正确。
【解决方案2】:

代替

formGroup[prop] = new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));

尝试向表单添加控件,它对我有用。您可以使用 form.addControl 来做到这一点:

formGroup.addControl(prop, new FormControl(res['com'][element]['schema']['properties'][prop].value || '', this.mapValidators(res['com'][element]['schema']['properties'][prop].validation));

【讨论】:

    【解决方案3】:

    我还需要进一步优化这个结果,以便我只听特定的表单控件?? ,我有一些不同的解决方案可以满足您的要求。

    template.html

    <form (ngSubmit)="custom_submit(form.value)" [formGroup]="form" >
     <div *ngFor="let input1 of newfdata[tabname].properties">   
      <ng-container *ngIf="input1.type=='string'">
       <div>
        <mat-form-field>
         <input matInput (ngModelChange)="modelChanged($event,input1.field_name)"[formControlName]="input1.field_name" [id]="input1.field_name" type="text"  placeholder="{{input1.title}}">
        </mat-form-field>   
       </div>
      </ng-container>
     </div>  
    </form>
    

    component.ts

     public modelChanged(ev, formName) {
       console.log('Jarvis Event', ev);
       console.log('control value', this.form.get(formName).value);
     }
    

    【讨论】:

      【解决方案4】:

      我们可以使用 表单控件 对象在特定的动态表单 HTML 元素上创建事件。 例如

      this.form.controls["DynamicFormControlId"].valueChanges.subscribe(val => {
      
          });
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2017-12-18
        • 2018-09-06
        • 1970-01-01
        • 2018-10-08
        • 2019-04-23
        • 2021-11-21
        • 1970-01-01
        • 2019-05-03
        相关资源
        最近更新 更多