我正在做一個小的 Angular 專案,但是我在使用 FormGroup 中的控制元件時遇到了問題,FormGroup 位于 FormArray 中。2個控制元件“name”和“hc”作業正常,但是另一個formGroup中的“hole1”讓我很煩。請問有什么幫助嗎?
TS
import { Component, OnInit } from '@angular/core';
import { FormGroup,FormArray, FormBuilder } from '@angular/forms'
@Component({
selector: 'app-scorecard',
templateUrl: './scorecard.component.html',
styleUrls: ['./scorecard.component.scss']
})
export class ScorecardComponent implements OnInit{
title = 'FormArray Example in Angular Reactive forms';
roundForm: FormGroup;
constructor(
private fb:FormBuilder
) {}
ngOnInit(): void {
this.roundForm = this.fb.group({
name: 'Round',
persons: this.fb.array([this.newPerson()])
});
}
get persons() : FormArray {
return this.roundForm.get("persons") as FormArray
}
newPerson(): FormGroup {
return this.fb.group({
name: '',
hc: '',
holes: this.fb.group({
hole1: null
})
})
}
addPerson() {
this.persons.push(this.newPerson());
}
removePerson(i:number) {
this.persons.removeAt(i);
}
onSubmit() {
console.log(this.roundForm.value);
}
}
HTML
<form [formGroup]="roundForm" (ngSubmit)="onSubmit()">
<!-- <strong>
{{roundForm.get('name')}}
</strong> -->
Persons:
<div formArrayName="persons">
<div *ngFor="let person of persons.controls; let i=index">
<div [formGroupName]="i">
{{i}} <br>
<input type="text" formControlName="name"> <br>
<input type="text" formControlName="hc">
**I want input with hole1 here**
<button (click)="removePerson(i)">Remove</button>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
<button type="button" (click)="addPerson()">Add</button>
<pre>{{this.roundForm.value | json}}</pre>
uj5u.com熱心網友回復:
你只需要指定hole組表單控制元件,然后使用內部表單控制元件名稱:
...
<input type="text" formControlName="name"> <br>
<input type="text" formControlName="hc">
<div formGroupName="holes">
<input type="text" formControlName="hole1">
</div>
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493813.html
下一篇:Angular專案不顯示更改
