为什么输入和选择框没有填写其值

时间:2017-02-20 23:10:13

标签: angular

我有一个表格,使用嵌套创建,显示带有电话号码的输入和选择以选择电话号码的类型。最初,我在创建formGroup时尝试分配一组值。但是当选择框得到它们的选项时,它不会选择预定义的值。输入框也不会收到预定义的值。

app.component.ts:57中,我正在使用我的预定义数组并单独解析它们并调用addPhoneForm方法。

addPhoneForm方法也使用initPhoneForm方法。这些一起创建了可以在app.component.html的第33行看到的电话表格。

我认为没有填写的原因是因为我还在我的PhoneDetailComponent构造函数中执行以下代码:

this.phoneForm = this.formBuilder.group({
    phoneNumber: new FormControl(),
    phoneType: new FormControl()
})

但是如果没有那段代码,我会收到一条错误,指出formGroup需要一个FormGroup。

这是我正在做的工作的一部分。 http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p=preview

- 代码块 -

- phone-detail.component.ts

export class PhoneDetailComponent {

    phoneTypes: EnumProperty[] = [];
    phoneForm: FormGroup;

    @Input('group')
    @Output() rawChange: EventEmitter<string> = new EventEmitter<string>();


    constructor(private phoneTypeService: PhoneTypeService,
                private formBuilder: FormBuilder) {
      this.getPhoneTypes();
      this.phoneForm = this.formBuilder.group({
        phoneNumber: new FormControl(),
        phoneType: new FormControl()
      })
    }

    private getPhoneTypes() {
      this.phoneTypeService.get()
        .then(phoneTypes => {
          this.phoneTypes = phoneTypes;
        })
    }

}

- app.component.html:31-36

  <div formArrayName="phones">
    <div *ngFor="let phone of updateProfileForm.controls.phones.controls; let i=index">
      <phone [group]="updateProfileForm.controls.phones.controls[i]"></phone>
    </div>
  </div>
  <a (click)="addPhoneForm()">+ Add another phone number</a>

- app.component.ts(仅限相关部分)

export class AppComponent {

  private version: any;
  updateProfileForm: FormGroup;

  phoneNumbers: PhoneModel[] = [
    { phoneNumber: "843-555-5849", type: "sms" },
    { phoneNumber: "756-555-7643", type: "home"},
    { phoneNumber: "395-555-9324", type: "tty" },
    { phoneNumber: "621-555-2690", type: "sms" }
  ]

  private phoneValidator = Validators.compose([
    Validators.minLength(7),
    Validators.maxLength(16),
    Validators.pattern(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/) ]);

  constructor(http: Http,
              private formBuilder: FormBuilder) {
    // Display the currently used Material 2 version.
    this.version = http
      .get('https://api.github.com/repos/angular/material2-builds/commits/HEAD')
      .map(res => res.json())

      this.updateProfileForm = this.formBuilder.group({
        personNames: ['', []],
        phones: this.formBuilder.array([])
      });

      console.log("Loading phones");
      this.phoneNumbers.forEach(p => this.addPhoneForm(p));
  }

  private addPhoneForm(p?: PhoneModel) {
    if (!p) {
      p.phoneNumber = "";
      p.type = PHONE_TYPES[0];
    }

    const control = <FormArray>this.updateProfileForm.controls['phones'];
    const phnCtrl = this.initPhoneForm(p);

    console.log(p);

    control.push(phnCtrl);
  }

  private initPhoneForm(phoneModel: PhoneModel) {
    console.log(phoneModel);
    return this.formBuilder.group({
      phoneNumber: [ phoneModel.phoneNumber, this.phoneValidator ],
      phoneType: [ phoneModel.type, [] ]
    });
  }
}

1 个答案:

答案 0 :(得分:0)

我终于明白了。首先,在PhoneDetailComponent类中,我们不需要FormBuilder。它只会让事情混乱。更特别的是,它之所以存在,是因为一个令人困惑的错误消息,这有助于建议我添加它。问题不在于FormBuilder,而是我发送给PDC类的属性不匹配。

工作结果如下:http://plnkr.co/edit/qv1BX7WtpYhw5B92SuoC?p=preview

(这个演示应用程序还有一个md-chip演示版。我还没有解决这个问题中描述的问题:How to set the select element's value of a dynamically created form in angular2

以下是PhoneDetailComponent类的外观:

export class PhoneDetailComponent {

    @Input('group')
    phoneForm: FormGroup;
    phoneTypes: EnumProperty[];

    constructor(private phoneTypeService: PhoneTypeService) {
      this.getTypes();
    }

    getTypes() {
      this.phoneTypeService.get()
        .then(phoneTypes => {
          this.phoneTypes = phoneTypes;
        });
      }
}

不好意思......我没有发布phone-detail.component.html相关代码。但我可能犯了一个错误。这是html应该是什么样子。请注意,phoneTypes是option元素的* ngFor的一部分。我有这个正确的。我可能遇到的错误是formControlNames。

<div [formGroup]="phoneForm">
    <div class="form-group col-xs-6">
        <md-input-container>
            <input mdInput
                   type="text"
                   placeholder="Phone"
                   formControlName="phoneNumber"
                   (rawChange)="rawPhone=$event"
                   [attr.maxlength]="14"
            >
            <md-hint *ngIf="phoneForm.controls['phoneNumber'].hasError('required') && phoneForm.controls['phoneNumber'].touched"
                     class="text-danger">
                Phone number is required
            </md-hint>
            <md-hint *ngIf="phoneForm.controls['phoneNumber'].hasError('minlength') && phoneForm.controls['phoneNumber'].touched"
                    class="text-danger">
                Phone number is to be 10 numbers long
            </md-hint>
        </md-input-container>
    </div>
    <div class="form-group col-xs-6">
        <label>Phone Type</label>
        <select class="form-control" formControlName="phoneType">
            <option *ngFor="let type of phoneTypes"
                    value="{{type.code}}" 
                    title="{{type.description}}">
              {{type.name}}
            </option>
        </select>
    </div>
</div>

app.component.ts文件是我初始化手机组件的地方。确保将formControlNames与您在组中设置的内容相匹配。

  private addPhoneForm(p?: PhoneModel) {
    const control = <FormArray>this.updateProfileForm.controls['phones'];
    const phnCtrl = this.initPhoneForm(p);

    control.push(phnCtrl);
  }

  private initPhoneForm(phoneModel?: PhoneModel) {
    let pModel: PhoneModel = {
      phoneNumber: "",
      type: PHONE_TYPES[0]
    }

    if (phoneModel) {
      pModel = phoneModel;
    }

    return this.formBuilder.group({
      phoneNumber: [ pModel.phoneNumber, this.phoneValidator ],
      phoneType: [ pModel.type ]
    });
  }