【发布时间】:2019-05-01 20:18:24
【问题描述】:
我正在尝试根据属性值显示数组中的单个对象。
我的交易项列表有一个 accountId 属性,但我想改为显示帐户名称。所有帐户都加载到 accounts$ 数组中。我只是不知道如何正确使用我的 getAccountById 函数
这里是组件类
export class NewtransactionComponent implements OnInit {
transaction$: Transaction;
tempItem$: TransactionItem;
accounts$: Array<Account>;
constructor(private data: DataService) { }
ngOnInit() {
this.transaction$ = new Transaction();
this.data.getAccounts().subscribe(data => this.accounts$ = Object.assign(new Array<Account>(), data));
this.tempItem$ = new TransactionItem();
this.transaction$.TransactionDate = new Date();
}
addItem(){
this.transaction$.TransactionItems.push(this.tempItem$);
this.tempItem$ = new TransactionItem();
}
getAccountById(id):Account{
return this.accounts$.find(x => x.id === id);
};
这是给出错误“无法读取未定义的属性'名称'”的 html 视图
<div class="items-container">
<mat-form-field>
<input matInput placeholder="Amount" [(ngModel)]="tempItem$.Amount">
</mat-form-field>
<mat-form-field *ngIf="accounts$">
<mat-select placeholder="Account" [(ngModel)]="tempItem$.AccountId">
<mat-option *ngFor="let account of accounts$" [value]="account.id">{{account.name}}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="Credit/Debit" [(ngModel)]="tempItem$.CreditDebit">
<mat-option value="Credit">Credit</mat-option>
<mat-option value="Debit">Debit</mat-option>
</mat-select>
</mat-form-field>
<button mat-mini-fab color="primary" (click)="addItem()">Add</button>
</div>
<table *ngIf="transaction$.TransactionItems.length">
<tr>
<th>Amount</th>
<th>Account</th>
<th>Credit/Debit</th>
</tr>
<tr *ngFor="let item of transaction$.TransactionItems">
<th>{{item.Amount | currency}}</th>
<th>{{getAccountById(item.AccoundId).name}}</th>
<th>{{item.CreditDebit}}</th>
</tr>
</table>
这些是可供参考的帐户和事务项数据模型
export class Account {
Id: string;
Name: string;
Category: string;
SubCategory: string;
}
export class TransactionItem{
Id: number;
TransactionId:number;
Accountid: string;
Amount: number;
CreditDebit: string;
}
【问题讨论】:
-
为什么在变量名中使用美元符号?通常,这用于indicate it is an observable?此外,如果您包含minimal reproducible example,您将获得更好的帮助。最后,如果没有一些样本数据,很难回答。我们只会猜测,假设您的类型正确匹配您的数据结构。
-
我是 Angular 新手,我认为 $ 是用于全局变量之类的。谢谢你让我知道,我现在修正了我的变量名。下次我会努力做一个更好的例子。我只是觉得我在语法上遗漏了一些基本的东西。