我一直在尝试将我的角度HTML模板中的表单数据绑定到我的Component中的接口。
我一直在关注以下教程,但我的FormGroup并没有像教程那样自动转换到后端的界面。
我的代码如下:
import { Component, OnInit } from "@angular/core";
import { FormGroup, FormBuilder, FormArray, FormControl, Validators } from "@angular/forms";
import { DeckBuildRequest } from "../domain-models/interfaces/deckBuildRequest.interface";
@Component({
selector: "deck-options",
templateUrl: "./deck-options.component.html",
styleUrls: ["./deck-options.component.css"]
})
export class DeckOptionsComponent {
private deckBuildRequest: FormGroup;
constructor(formBuilder: FormBuilder) {
this.deckBuildRequest = formBuilder.group({
"deckSize": 60,
"deckColors": formBuilder.array([
{color: "Blue", checked: false},
{color: "Green", checked: false},
{color: "Red", checked: false},
{color: "White", checked: false},
{color: "Black", checked: false},
{color: "Colorless", checked: false}
])
});
}
GenerateDeck(request: DeckBuildRequest) {
alert(request.deckSize);
}
}
<div id="deck-options">
<form [formGroup]="deckBuildRequest"
(ngSubmit)="GenerateDeck(deckBuildRequest)">
<span>
<label><input formControlName="deckSize" type="number" max="100" min="1">Number of Cards</label>
</span>
<div>
<label [attr.for]="'color'+i"
*ngFor="let colorOption of deckBuildRequest.controls['deckColors'].controls, let i = index"
>
<input
type="checkbox"
id="color{{i}}"
value="{{colorOption.value.color}}"
ng-checked="colorOption.value.checked"
/>
{{colorOption.value.color}}
</label>
</div>
<button type="submit">Generate Deck!</button>
</form>
</div>
export interface DeckBuildRequest {
deckSize: number;
deckColors: [{
color: string;
checked: boolean;
}];
}
我在这里缺少什么?
答案 0 :(得分:1)
FWIW,我得到了隐式映射。您可以从View传递formGroup的值,并隐式地转换为Component端的接口。
通过调用&#34; .getRawValue()&#34;简单地传递FormGroup结构值。到期望接口作为隐式转换参数的组件。
答案 1 :(得分:0)
Thread
将其替换为html表单。这对我有用。