在父/子 Angular 组件之间共享表单结果?

huangapple go评论70阅读模式
英文:

Share a form result between parent/child angular components?

问题

我使用子组件中的选择器将表单模板传递到另一个父组件中。这个表单有一些可以选择的选项,我想要获取用户选择的结果并在子组件中处理它。

在父组件中,你可以通过 responseEvent 事件来获取用户在子组件中所选择的值。在子组件中,当用户选择某个值时,使用 this.responseEvent.emit(this.form); 将表单数据发送到父组件,然后在父组件的 onFormGroupChangeEvent 方法中,你可以获取并处理这个值。如下所示:

在子组件中:

public onChangeEvent(_event) {
  this.responseEvent.emit(this.form);
  this.form.addControl('simple', new FormGroup(this.form.controls));
}

在父组件中:

public onFormGroupChangeEvent(_form) {
  this.form = _form;
  console.log("form", _form);
  // 在这里你可以处理用户所选择的值
}

这样,当用户在子组件中选择某个值时,父组件中的 onFormGroupChangeEvent 方法会被触发,你可以在这个方法中处理用户所选择的值。

英文:

I have a form inside a child component and I use that component's selector to pass the form template inside another parent component.
This form has some options to be selected and I would like to get the result selected by the user and handle it inside the child component.

I'm using an event in the parent component but it's not working. I want to get what was selected inside the simple formControlName.

CHILD HTML

<form formGroup="form" autocomplete="off" (change)="onChangeEvent($event)">
  <voxel-likert formControlName="simple" (change)="onChangeEvent($event)">
    O que você achou dessa nova experiência?
  </voxel-likert>
  <div *ngIf="form.controls.simple.value" >
    {{ form.controls.simple.value | json }}
  </div>
</form>

CHILD COMPONENT

export class MyComponent implements OnInit {

  @Input() form = new FormGroup({
    simple: new FormControl(''),
  });


  @Output() responseEvent = new EventEmitter<any>();

  constructor() {}

  ngOnInit(): void {

    this.responseEvent.emit(this.form);
    console.log('form likert', this.form.value);

  }

  public onChangeEvent(_event){
    this.responseEvent.emit(this.form);

    this.form.addControl(
      'simple',
      new FormGroup(this.form.controls)
    );

  }
}

PARENT HTML

<ui-likert 
  (responseEvent)="onFormGroupChangeEvent($event)"></ui-likert>

PARENT COMPONENT

export class ParentComponent

{
  form = new FormGroup({
    simple: new FormControl(''),
  });

  public onFormGroupChangeEvent(_form) {
    this.form = _form;
    console.log("form",_form);

  }


}

How do I get the value that the user is selecting in the parent component? but I want to get this value inside the child component

答案1

得分: 0

在Angular中,@Input() 是一个引用。因此,如果您将一个引用传递给子组件,您仍然可以从父组件或子组件访问属性,调用方法等。

在这种情况下,通过 @Output(自定义事件发射器)将信息发送回父组件是不必要的,因为引用是在父组件上创建的,因此即使子组件修改引用,也是可访问的。

以下是一个示例,展示了即使表单由子组件渲染,也可以在父组件上看到响应式表单的值如何变化:

// parent.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-parent',
  template: `
    <app-child-component [form]="form"></app-child-component>

    Form Value: {{ form.value | json }}
  `,
})
export class ParentComponent implements OnInit {

  form!: FormGroup;

  ngOnInit(): void {
    this.form = new FormGroup({
      field1: new FormControl(''),
    });

    this.form.valueChanges.subscribe(value => {
      // do something
    });
  }

}

// child.component.ts

import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';

@Component({
  selector: 'app-child',
  template: `
    <form *ngIf="form" [formGroup]="form" role="form">
      <label for="field1">Field 1</label>
      <input formControlName="field1" id="field1" type="text" />
    </form>
  `,
})
export class ChildComponent {

  @Input()
  form!: FormGroup;

}

如果在子组件中修改表单的 field1 值,它的值将在父组件中反映出来。

您还可以在父组件中订阅 valueChanges(),以便在表单值更改时得到通知,并可以对该值执行一些操作。

希望对您有所帮助。

英文:

In Angular, @Input() is a reference. As such, if you pass a reference to a child component, you can still access the properties, call methods, etc on your reference from the parent or child.

Sending information back to the parent in this case via @Output (a custom event emitter) isn't necessary, as the reference is created on the parent and therefore accessible, even if the child modifies the reference.

Here's an example of how you can see the values of a reactive form change on the parent, even though the form is rendered by the child:

// parent.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;
import { FormControl, FormGroup } from &#39;@angular/forms&#39;;

@Component({
  selector: &#39;app-parent&#39;,
  template: `
    &lt;app-child-component [form]=&quot;form&quot;&gt;&lt;/app-child-component&gt;

    Form Value: {{ form.value | json }}
  `,
})
export class ParentComponent implements OnInit {

  form!: FormGroup;

  ngOnInit(): void {
    this.form = new FormGroup({
      field1: new FormControl(&#39;&#39;),
    });

    this.form.valueChanges.subscribe(value =&gt; {
      // do something
    });
  }

}

// child.component.ts

import { Component, Input } from &#39;@angular/core&#39;;
import { FormGroup } from &#39;@angular/forms&#39;;

@Component({
  selector: &#39;app-child&#39;,
  template: `
    &lt;form *ngIf=&quot;form&quot; [formGroup]=&quot;form&quot; role=&quot;form&quot;&gt;
      &lt;label for=&quot;field1&quot;&gt;Field 1&lt;/label&gt;
      &lt;input formControlName=&quot;field1&quot; id=&quot;field1&quot; type=&quot;text&quot; /&gt;
    &lt;/form&gt;
  `,
})
export class ChildComponent {

  @Input()
  form!: FormGroup;

}

If you modify the value of field1 on the form in the child, it's value will be reflected in the parent.

You can also subscribe to the valueChanges() in the parent to be notified whenever the form value changes, and you could do something with the value.

Hope that helps you out.

huangapple
  • 本文由 发表于 2023年3月7日 00:49:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653588.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定