微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

core.js:5980 错误类型错误:无法读取未定义的属性“名称”角度

如何解决core.js:5980 错误类型错误:无法读取未定义的属性“名称”角度

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

我的模型:

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 上

解决方法

是否有特殊需要使用 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>
,

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

<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了解更多详情。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。