首页 文章

没有名称的表单控件的值访问器:'rating'在带有Reactive Froms的Angular 2 mat-dialog中

提问于
浏览
1

我有这个评论对话框组件:

export class ReviewDialogComponent implements OnInit {

  form: FormGroup;
  comments: string;
  rating: number;

  constructor(
    private fb: FormBuilder,
    private dialogRef: MatDialogRef<ReviewDialogComponent>,
    @Inject(MAT_DIALOG_DATA) data) {

   this.comments = data.comments;
   this.rating = data.rating;

   this.form = fb.group({
     comments: [this.comments, []],
     rating: [this.rating, []]
  });
  }
  ngOnInit() {
   }
  save() {
    this.dialogRef.close(this.form.value);
   }
  close() {
   this.dialogRef.close();
  }
}

html:

<mat-dialog-content [formGroup]="form">

   <mat-form-field>
     <textarea matInput
            placeholder="Comments"
            formControlName="comments">
     </textarea>
   </mat-form-field>

   <mat-form-field>
     <mat-select placeholder="Select rating"
            formControlName="rating">

      <mat-option value="1">1</mat-option>
      <mat-option value="2">2</mat-option>
      <mat-option value="3">3</mat-option>
      <mat-option value="4">4</mat-option>
      <mat-option value="5">5</mat-option>
     </mat-select>
  </mat-form-field>

</mat-dialog-content>

用法:

addReview() {
   const dialogConfig = new MatDialogConfig();

   dialogConfig.disableClose = true;
   dialogConfig.autoFocus = true;

   dialogConfig.data = {
      comments: '',
      rating: null
   };

   const dialogRef = this.dialog.open(ReviewDialogComponent,
      dialogConfig);

   dialogRef.afterClosed().subscribe(
      val => console.log("Dialog output:", val)
    );
}

我有所需的所有导入,它加载对话框,但它会在几秒钟后返回错误 . 我已经尝试添加 ngDefaultControl 但之后我收到了"Error: mat-form-field must contain a MatFormFieldControl."所以它没有't really help. Also, I'已经检查angular2 rc.5 custom input, No value accessor for form control with unspecified name,没有帮助 . 我错过了什么?

非常感谢 !

1 回答

  • 0

    重命名您的表单名称,因为它是保留的关键字 . 并在ngOnInit()中以这样的形式传递数据,而不是在构造函数中:

    ngOnInit() {
        this.feedbackForm = fb.group({
        comments: [this.comments],
        rating: [this.rating]
        });
    }
    

    删除空的验证方括号 .

相关问题