错误类型错误:无法读取 Angular 中未定义的属性“标题”

时间:2021-03-14 13:55:01

标签: node.js angular typescript angular-material

post-create.component.html 控制台上的错误信息

错误类型错误:无法读取 PostCreateComponent_Template (template.html:13) 处未定义的属性“标题”

我认为问题出在 console.log(form.value.title, form.value.content);

post-create.component.html

<mat-card>
  <form (submit)="onAddPost(postform)" #postform="ngForm">
    <mat-form-field>
      <input
        matInput
        type="text"
        name="title"
        [ngModel]="post.title"
        required
        #title="ngModel"
        placeholder="Enter Post Title"
      />
      <mat-error *ngIf="title.invalid">Please enter a post title.</mat-error>
    </mat-form-field>
    <mat-form-field>
      <textarea
        matInput
        rows="6"
        name="content"
        [ngModel]="post.content"
        required
        #content="ngModel"
        placeholder="Enter Post Content"
      ></textarea>
      <mat-error *ngIf="content.invalid">Please enter a post title.</mat-error>
    </mat-form-field>
    <button mat-raised-button color="primary" type="submit">Add Post</button>
  </form>
</mat-card>

post-create.component.ts(上述 html 文件的 ts 文件)请检查并帮助我解决错误信息,提前谢谢!!!

import { Component, OnInit, EventEmitter, Output } from "@angular/core";
import { NgForm } from "@angular/forms";
import { ActivatedRoute, ParamMap } from "@angular/router";
import { Posts } from "../post.model";
import { PostService } from "../post.service";

@Component({
  selector: "app-post-create",
  templateUrl: "./post-create.component.html",
  styleUrls: ["./post-create.component.css"],
})
export class PostCreateComponent implements OnInit {
  constructor(public postservice: PostService, public route: ActivatedRoute) {}
  private postId: string;
  private mode = "create";

  post: Posts;
  ngOnInit() {
    this.route.paramMap.subscribe((paramMap: ParamMap) => {
      if (paramMap.has("postId")) {
        console.log(paramMap.get("postId"));
        this.mode = "edit";
        this.postId = paramMap.get("postId");

        this.post = this.postservice.getPosts(this.postId);
        console.log(this.post);
      } else {
        this.mode = "create";
        this.postId = null;
      }
    });
  }

  onAddPost(form: NgForm) {
    if (form.invalid) {
      return;
    }

    if (this.mode === "create") {
      console.log(form.value.title, form.value.content);
      this.postservice.addPosts(form.value.title, form.value.content);
    } else {
      this.postservice.updatePost(
        this.postId,
        form.value.title,
        form.value.content
      );
    }
    // this.postservice.addPosts(form.value.title, form.value.content);
    form.resetForm();
  }
}

1 个答案:

答案 0 :(得分:2)

当您像在此 [ngModel]="post.title" 那样使用带有对象属性的 ngModel 时,您必须在其声明、类构造函数或 ngOnInit 方法中使用空对象初始化对象。 所以,像这样的 post: Posts = { title: null, content: null }; 可能会解决这个问题。