代码之家  ›  专栏  ›  技术社区  ›  Johan Rin

错误类型错误:提交表单后无法读取未定义的属性“text”

  •  1
  • Johan Rin  · 技术社区  · 6 年前

    提交表单后,控制台中出现此错误:

    错误类型错误:无法读取未定义的属性“text”

    将Submit方法传递给带有输出修饰符的哑组件。

    在我的代码下面:

    注释.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();
      }
    
    }
    

    注释.component.html

    <div class="component-container">
    
      [...]
    
      <app-comments-form
        [commentForm]="commentForm"
        (submit)="onSubmitRequestComment($event)">
      </app-comments-form>
    
    </div>
    

    注释-表单.组件.ts

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

    注释-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 回复  |  直到 6 年前
        1
  •  0
  •   Arash    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

      newComment.text = this.commentForm.value.text as string;