Angular-TypeError:无法读取未定义的属性“名称”

时间:2019-04-16 14:25:39

标签: html angular typescript

我不太确定如何以更好的方式表达问题,但我 需要一些帮助以了解如何解决此问题。以下是我的错误:

  1. <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js"></script>
  2. $digest = hash("sha512", $salted, true);

当我尝试在html中使用TypeError: _co.create is not a function时,它将在控制台中引发这些错误。所以我认为问题出在HTML之内。

newCategory CreateCategoryComponent.ts

中定义
TypeError: Cannot read property 'name' of undefined

CategoryService.ts

newCategory.name

CreateCategory.html

newCategory: Category;
name: string;
description: string;

3 个答案:

答案 0 :(得分:2)

您的组件具有3个属性:

  • newCategory:类别;
  • 名称:字符串;
  • 说明:字符串;

然后,您需要设置/获取属性名称,您将使用:name

<td><input id="name" name="name" #name="ngModel" type="text" [(ngModel)]="name" required="true" /></td>

或者您需要将name添加到newCategory对象中

newCategory: Category = {
    name: string, 
    description: string
};

并在模板中使用newCategory.name

<td><input id="name" name="name" #name="ngModel" type="text" [(ngModel)]="newCategory.name" required="true" /></td>

希望获得帮助!

答案 1 :(得分:1)

HTML没问题。

问题是newCategory: Category;,因为值未初始化。您在这里所做的只是将newCategory设置为type of类别。

您可以通过以下方式初始化newCategory:

  1. 使用new运算符
       newCategory: Category = new Category();
  1. 我通常在Category模型文件中声明初始状态,然后将其导入到适当的文件中。
    export const initialState: Category = {
      name: '',
      description: ''
    };
  1. 初始化组件中的值
    newCategory: Category = {
      name: '',
      description: ''
    };

答案 2 :(得分:0)

在从异步调用返回对象之前加载页面时,我发生了这种情况。我的解决方案是 *ngIf 块。

<div *ngIf="object"><br />
<b>{{ object.property1}}</b><br />
<i>{{ object.property2}}</i><br />
</div>