【问题标题】:Cannot read property 'title' of undefined MEAN app无法读取未定义的 MEAN 应用程序的属性“标题”
【发布时间】:2021-08-19 14:35:13
【问题描述】:

我一直收到此错误,我的表单不会显示。

这是代码:

<mat-card>
  <form (submit)="onSavePost(postForm)" #postForm="ngForm">
    <mat-form-field>
      <input
        matInput
        type="text"
        name="title"
        [ngModel]="post.title"
        required
        minlength="3"
        #title="ngModel"
      />
      <mat-error *ngIf="title.invalid">Please enter a post title.</mat-error>
    </mat-form-field>
    <mat-form-field appearance="fill">
      <input
        matInput
        [ngModel]="post.content"
        name="content"
        required
        #content="ngModel"
      />
      <mat-error *ngIf="content.invalid">Please enter content</mat-error>
    </mat-form-field>
    <button mat-raised-button color="accent" type="submit">Save Post</button>
  </form>
</mat-card>

还有错误图片:

有什么想法吗?纠结了好久哈哈,求大神帮忙

【问题讨论】:

  • 请检查post值。

标签: angular database mean


【解决方案1】:

title 属性只有一次调用:post.title。似乎post 未定义。可能页面是在post 加载之前渲染的。

【讨论】:

  • 我不这么认为,这是我的代码enteredTitle = ''; enteredContent = ''; post: Post; private mode = 'create'; private postId: string; ngOnInit() { this.route.paramMap.subscribe((paramMap: ParamMap) =&gt; { if (paramMap.has('postId')) { this.mode = 'edit'; this.postId = paramMap.get('postId'); this.post = this.postsService.getPost(this.postId); } else { this.mode = 'create'; this.postId = null; } }); }
  • post 属性的初始值未定义。渲染将在路由参数的订阅触发之前发生。因此,我提供的答案准确地描述了正在发生的事情。接受的答案适用于这种情况,因为this.postsService.getPost 是同步方法。如果使用异步,用户体验会很差
【解决方案2】:

当您调用 post.title 时,post 尚未定义。

试试这个:

[ngModel]="post?.title"

【讨论】:

  • 不,不是我的朋友
  • 好的,你确定你在 paramMap 中有 postId 吗?
猜你喜欢
  • 2018-11-30
  • 2021-11-03
  • 1970-01-01
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 2019-03-27
  • 2020-09-12
相关资源
最近更新 更多