【问题标题】:core.js:5980 ERROR TypeError: Cannot read property 'Name' of undefined (angular)core.js:5980 错误类型错误:无法读取未定义的属性“名称”(角度)
【发布时间】:2021-04-23 15:38:52
【问题描述】:

我无法生成带有角度信息的卡片

我的模特:

export class order {
    Name!: string
    Surname!: string
    Email!: string
    Type!: string
    Description!: string

    constructor(name: string, surname: string, email: string, type: string, desc: string) {
        this.Name = name,
            this.Surname = surname,
            this.Email = email,
            this.Type = type,
            this.Description = desc
    }
}

卡片组件打字稿:

import { Component, Input, OnInit } from '@angular/core';
import { order } from 'src/app/shared models/order.model';

@Component({
  selector: 'app-contact-card',
  templateUrl: './contact-card.component.html',
  styleUrls: ['./contact-card.component.css']
})
export class ContactCardComponent implements OnInit {
  @Input()
  item!: order;
  constructor() { }

  ngOnInit(): void {
  }

}

卡片组件html:

<div class="card">
    <h3>{{item.Name}} {{item.Surname}}</h3>
    <div class="flex">
        <p>{{item.Email}}</p>
        <p>{{item.Type}}</p>
    </div>
    <p>{{item.Description}}</p>
</div>

当我插入字符串时,它说错误出现在我的 html 上

【问题讨论】:

    标签: angular model string-interpolation angular-event-emitter


    【解决方案1】:

    请检查item 的值。可能是null 或undefined,这就是发生此错误的原因。为避免此错误,请尝试以下操作:

    <div class="card">
        <h3>{{item?.Name}} {{item?.Surname}}</h3>
        <div class="flex">
            <p>{{item?.Email}}</p>
            <p>{{item?.Type}}</p>
        </div>
        <p>{{item?.Description}}</p>
    </div>
    

    阅读Safe navigation operator (?.) or (!.) and null property paths了解更多详情。

    【讨论】:

      【解决方案2】:

      是否有特定需要为order 使用类?类需要被实例化。如果它不包含方法并且没有明确的需要,我建议您改用 TS Interface。它允许进行类型检查而没有类附带的“膨胀”。

      export interface order {
          Name!: string;
          Surname!: string;
          Email!: string;
          Type!: string;
          Description!: string;
      }
      

      然后您可以在 Angular 模板中使用安全导航运算符 ?. 以避免潜在的 undefined 错误。它会在尝试访问它的属性之前检查对象是否已定义。

      <div class="card">
          <h3>{{item?.Name}} {{item?.Surname}}</h3>
          <div class="flex">
              <p>{{item?.Email}}</p>
              <p>{{item?.Type}}</p>
          </div>
          <p>{{item?.Description}}</p>
      </div>
      

      【讨论】:

        猜你喜欢
        • 2019-11-16
        • 1970-01-01
        • 2018-12-04
        • 1970-01-01
        • 2020-03-02
        • 2020-07-22
        • 2021-04-05
        • 2021-03-12
        • 2019-07-26
        相关资源
        最近更新 更多