簡體   English   中英

如何在 angular 反應式 forms 中使用子組件?

[英]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,並且您可以使用更改掛鈎將子組件表單的值發送給父組件。

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

然后在您的父組件中,您可以處理發出的值並設置表單控件

父組件.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>

父組件.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])
}
}

我認為這應該工作,希望這會幫助你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM