材质2表单控件选择不使用Async Source

时间:2017-10-27 00:13:29

标签: angular angular-material2 angular4-forms

我正在使用Material 2.0.0-beta.12运行Angular 4.3.4并且在尝试创建mat-select以从异步源生成动态mat-option列表时遇到问题。我得到的只是占位符,下拉列表不会扩展。我甚至都收不到错误代码。

以下是我的代码更新

的示例
 <form [formGroup]="snoozeForm" novalidate>
  <div fxLayout="column">
    <mat-form-field>
      <mat-select formControlName="snooze_reason">
        <mat-option [value]="reason.attributes.snooze_reason_code" *ngFor="let reason of reasons">{{ reason }}</mat-option>
      </mat-select>
    </mat-form-field>
</form>

正如您所见,原因是动态填充的数组。我必须忽略一些简单的事情,但我确信原因正在填充。

这是我填充数组的地方:

ngOnInit() {
  this.generateForm();
  this.httpService.getSnoozeReasons()
    .subscribe( res => {
      this.reasons = res;
    }, (error: any) => {
      const msg: Message = { title: 'Frontend API Error', textbody1: '' };
      if (error.message) {
        msg.textbody1 = <any>error.message;
        msg.textbody2 = `Task-details component - Snooze reasons`;
      } else {
        msg.textbody1 = `HTTP ${error.status}: ${error.statusText}`;
        msg.textbody2 = `Task-details - Snooze reasons: ${error.url}`;
      }
      this.messageService.createMessage(msg);
    })
  ;
}

generateForm(): void {
  this.snoozeForm = this.fb.group({
    snooze_reason: ['', [Validators.required]],
    snooze_hour: ['', [Validators.pattern('[0-9]*'), Validators.max(72)]],
    snooze_minute: ['', [Validators.required, Validators.min(5), Validators.pattern('[0-9]*')]]
  });
}

enter image description here

是否有人遇到异步数据和选择表单控件的问题?

2 个答案:

答案 0 :(得分:1)

我认为问题不是async数组的原因,否则当你使用formControlName =&#34; snooze_reason&#34;时,如果你试着删除formcontrolname,&#34; select&#34;工作很好。这是因为Angular表单中的控件需要声明为表单组的子节点。

&#13;
&#13;
import {Component} from '@angular/core';
import {FormControl, FormGroup} from '@angular/forms';

@Component({
  selector: 'material-select-angular',
  templateUrl: 'material-select-angular.html',
})
export class MaterialSelectAngular implements OnInit {
  formParent = new FormGroup({
    snoozeReason: new FormControl()
  });
  reasons = [];
  
  ngOnInit(){
    setTimeout(() => {
      this.reasons = [
        {prop: 'something'},
        {prop: 'anything'},
        {prop: 'some'}
      ];
    }, 2000);
  }
}
&#13;
<form [formGroup]="formParent">
<mat-form-field>
  <mat-select formControlName="snoozeReason" placeholder="Favorite food">
    <mat-option *ngFor="let reason of reasons" [value]="reason.prop">
      {{ reason.prop }}
    </mat-option>
  </mat-select>
</mat-form-field>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

谢谢@Guillodacosta!

我有另一双眼睛来验证代码是否正确。我相信我现在的问题是我与我的UI包有冲突。 Ng-Bootstrap可能导致我的材质2选择无法正确渲染。

在过去的一个周末,我花了一些时间来复制我的场景,并验证我的代码应该使用填充Material 2 Select Drop-down的异步数据。