【发布时间】:2019-03-09 22:25:45
【问题描述】:
我正在尝试创建一个应用程序,让我可以将新用户添加到表中。我得到的错误是:
“类型'BugTableComponent'上不存在属性'user'”
我正在使用材料模板,但没有任何模板可以让我精确地做我想做的事情。据我了解,问题在于现有数组在bugTablecomponent 之外,因此无法找到。另一方面,如果我将数组放入组件中,则表格无法“访问”它。
有什么办法可以解决这样的问题?
对不起,我的技术语言很差,我是新手。
HTML:
<mat-table #table [dataSource]="myDataArray" class="mat-elevation-z8">
<ng-container matColumnDef="userName">
<th mat-header-cell *matHeaderCellDef>Name</th>
<td mat-cell *matCellDef="let user"> {{user.userName}} </td>
</ng-container>
<ng-container matColumnDef="age">
<th mat-header-cell *matHeaderCellDef>Age</th>
<td mat-cell *matCellDef="let user"> {{user.age}} </td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay">
</tr>
<tr mat-row *matRowDef="let dataSource; columns: columnsToDisplay"></tr>
</mat-table>
<p>
<mat-form-field apparence="legacy">
<mat-label>Name</mat-label>
<input matInput [(ngModel)]="user.userName" type="text" name="newuserName" id="newuserName" class="form-control">
</mat-form-field>
<mat-form-field apparence="legacy">
<mat-label>Age</mat-label>
<input matInput [(ngModel)]="user.age" type="text" name="newuserAge" id="newAge" class="form-control">
</mat-form-field>
</p>`enter code here`
<button mat-button type="button" (click)="addName()">submit</button>
打字稿:
export class BugTableComponent {
columnsToDisplay: string[] = ["userName", "age"];
myDataArray = USER_DATA;
addName() {
this.myDataArray.push(this.user);
this.user = {};
}
}
let USER_DATA: user[] = [
{ userName: "Wacco", age: 12 },
{ userName: "Wacca", age: 13 },
{ userName: "Waccu", age: 14 }
];
export interface user {
userName: string;
age: number;
}
【问题讨论】:
-
您可能需要另一个对象
user: User来引用接口User,以便您可以在其他地方使用它。您不能直接引用接口名称User并在其他地方访问其属性。 stackblitz.com/edit/… -
@AmitChigadani,只是一个谦虚的,出于好奇的问题。 Wiktor 已经定义了“用户”接口。为什么你认为定义一个新的界面“用户”会解决问题?
-
@Shahana 好吧,我没有要求创建新界面
User。我提到要为该接口创建一个引用或对象,称为user: User。我根据编码标准在我的评论中将接口名称user重构为User。如果不创建接口引用,我们就无法访问它的属性。
标签: arrays angular typescript html-table angular-material