【问题标题】:Why are the input and select boxes not filling in their values为什么输入框和选择框没有填写它们的值
【发布时间】:2017-02-20 23:10:13
【问题描述】:

我有一个使用嵌套创建的表单,它显示了一个带有电话号码的输入和一个选择电话号码类型的选项。最初,我有一组值,我试图在创建 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。

这是我正在做的事情的 plnkr。 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, [] ]
    });
  }
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    我终于明白了。首先,在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 是选项元素的 *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 ]
        });
      }
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      相关资源
      最近更新 更多