如何以角度反应形式使用子组件?

时间:2021-04-27 10:53:32

标签: angular 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>

请注意,我在这里只添加了一个子组件以提高可读性。我假设它们都一样。

1 个答案:

答案 0 :(得分:1)

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

我将使用 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])
}
}

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