将FormGroup映射到接口对象

时间:2017-06-22 19:53:37

标签: typescript angular2-template angular2-forms

我一直在尝试将我的角度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);
  }

}

HTML

<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;
    }];
}

我在这里缺少什么?

2 个答案:

答案 0 :(得分:1)

FWIW,我得到了隐式映射。您可以从View传递formGroup的值,并隐式地转换为Component端的接口。

http://www.angular2sucks.com/2017/03/23/convert-a-formgroup-in-an-object-and-use-it-as-you-are-supposed-to/

通过调用&#34; .getRawValue()&#34;简单地传递FormGroup结构值。到期望接口作为隐式转换参数的组件。

答案 1 :(得分:0)

Thread

将其替换为html表单。这对我有用。