如何在 angular 响应式表单中使用子组件?

How to use child components in angular reactive forms?

在我的 Angular 11.2.6 项目中,我有一个包含三个子组件的表单,所有子组件都接受用户输入。

我想将 formControl 附加到所有这些子组件,并在我的父组件中创建 formGroup。但是我不知道如何将子组件中的输入绑定到父组件中的表单组。

这是我的父组件html:

<form class="form__main" (ngSubmit)="onSubmit()">
  <h2>{{ 'choose_cryptocurrency' | translate }}</h2>

  <currency-selector></currency-selector>

  <coin-amount-input></coin-amount-input>

  <button class="button__submit--order" mat-raised-button color="primary">
    {{ 'submit_order' | translate }}
  </button>
</form>

这是我的父组件 ts:

exchangeBuyForm = new FormGroup({
    buyingCoin: new FormControl(''),
    payingCoin: new FormControl(''),
  });

这是我的子组件html(硬币数量输入):

<div class="wrapper__input">
  <mat-label>input currency</mat-label>
  <mat-form-field class="input__currency" appearance="fill">
    <input
      type="text"
      name="formattedNumberInput"
      class="mat-input-element"
      #formattedNumberInput
      [ngModel]="formattedValue"
    />
  </mat-form-field>
</div>

请注意,为了提高可读性,我在这里只添加了一个子组件。我假设它们都以相同的方式工作。

如果我很好地理解你的目的,我认为你必须避免 ngModel,并在所有子组件中创建一个 FormGroup,并且你可以使用 change hook 将子组件表单的值发送给父组件。

我将使用 angular 的 formBuilder 编写,.

child.component.html

<form [formGroup]="form"
  <div class="wrapper__input">
    <mat-label>input currency</mat-label>
    <mat-form-field class="input__currency" appearance="fill">
      <input
        type="text"
        name="formattedNumberInput"
        class="mat-input-element"
        (change)="emitFormValue()"
        #formattedNumberInput
        formControlName="numberInput"
      />
    </mat-form-field>
  </div>
</form>

child.component.ts

formValue = new EventEmitter<any>()

constructor(private fb: FormBuilder) {}

form = this.fb.group({
  numberInput: ['']
})

ngOnInit() {}

emitFormValue() {
  this.formValue.emit(this.form.value)
}

然后在您的父组件中,您可以处理发出的值并设置表单控件

parent.component.html

<form class="form__main" (ngSubmit)="onSubmit()">
  <h2>{{ 'choose_cryptocurrency' | translate }}</h2>

  <currency-selector (formValue)="onFormvalue($event)"></currency-selector> //assuming this is the child component

  <coin-amount-input></coin-amount-input>

  <button class="button__submit--order" mat-raised-button color="primary">
    {{ 'submit_order' | translate }}
  </button>
</form>

parent.component.ts

constructor(private fb: FormBuilder) {}

form = this.fb.group({
  numberInput: [''],
  otherField: [''],
})

ngOnInit() {}

onFormValue($event) {
  let value = $event
  let keys=Object.keys(value)
  keys.foreach(key => {
  this.form.get(key).setValue(value[key])
}

我认为这应该可行,希望对您有所帮助