错误TypeError:提交表单后无法读取未定义的属性'text'

时间:2018-07-30 10:11:45

标签: angular

提交表单后,我在控制台中遇到此错误:

  

错误TypeError:无法读取未定义的属性“文本”

submit方法被传递到带有输出装饰器的哑组件。

在我的代码下面:

comments.component.ts

export class CommentsComponent implements OnInit {
  commentForm: FormGroup;
  @Input() comments: Comment[];
  @Input() source: string;
  @Input() sourceId: string;

  constructor(
    private formBuilder: FormBuilder,
    private route: ActivatedRoute,
    private commentService: CommentService
  ) { }

  ngOnInit() {
    this.createForm();
  }

  createForm() {
    this.commentForm = this.formBuilder.group({
      text: ['', Validators.required]
    });
  }

  onSubmitRequestComment(commentForm: FormGroup) {
    let newComment = new Comment ({
      text: commentForm.value.text as string
    });

    this.commentService.addRequestComment(this.sourceId, newComment);
    this.commentForm.reset();
  }

}

comments.component.html

<div class="component-container">

  [...]

  <app-comments-form
    [commentForm]="commentForm"
    (submit)="onSubmitRequestComment($event)">
  </app-comments-form>

</div>

评论-form.component.ts

export class CommentsFormComponent {
  @Input() commentForm: FormGroup;
  @Output() submit = new EventEmitter<FormGroup>();

  constructor() { }

}

comments-form.component.html

<form class="form-container" [formGroup]="commentForm" (ngSubmit)="submit.emit(commentForm)">
  <mat-form-field class="form-field-container">
    <mat-label>
      <i class="far fa-comment-dots"></i> Write your comment...
    </mat-label>
    <input matInput formControlName="text">
  </mat-form-field>

  <div class="buttons-container">
    <button mat-button color="accent" type="submit">
      <i class="fas fa-check"></i> Confirm
    </button>
  </div>
</form>

如何解决此错误消息?

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在您的 onSubmitRequestComment 函数中,而不是

(1, 1)-->(1, 2), (1, 1)-->(1 3)...(1, 1)-->(1, 6)

使用

   let newComment = new Comment ({
      text: commentForm.value.text as string
    });

更新

功能

 let newComment = new Comment ();
  newComment.text = this.commentForm.value.text as string;

参数 onSubmitRequestComment(commentForm: FormGroup) { let newComment = new Comment ({ text: commentForm.value.text as string }); 没有值,所以commentForm为空 当然,您不能呼叫commentForm.value。 所以最好像

一样使用它
commentForm.value.text

并使用公共变量(this.commentForm)。