TypeError:无法读取属性' taxTypeId'在Object.View_FullEditTaxComponent_0._co [作为updateDirectives]的undefined

时间:2017-11-11 13:22:20

标签: angular typescript

我有一个详细信息表单,应该从列表表单中选择时加载记录的详细信息。加载详细信息表单时,它应该显示所选记录的详细信息。就我而言,它显示的细节非常好,但它在控制台上显示标题错误,导致应用程序崩溃。

HTML(错误行)

<select id="taxTypeId" name="TaxTypeId" [(ngModel)]="tax.taxTypeId" class="form-control" >
   <option *ngFor="let tt of taxTypes" value={{tt.id}}>{{tt.name}}</option>
</select>
<label for="taxTypeId" class="form-label">Tax Type</label>

打字稿

import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef, OnInit } from '@angular/core';
import { RouterLink, Router, ActivatedRoute } from '@angular/router';
import { TaxServiceProxy, TaxDto, ListResultDtoOfTaxTypeDto } from '../../../shared/service-proxies/tax-service-proxies';
import { TaxTypeDto } from '../../../shared/service-proxies/taxType-service-proxies';
import { AppComponentBase } from '@shared/app-component-base';

@Component({
  selector: 'app-full-edit-tax',
  templateUrl: './full-edit-tax.component.html',
  styleUrls: ['./full-edit-tax.component.css']
})
export class FullEditTaxComponent extends AppComponentBase implements OnInit {
  active: boolean = false;
  saving: boolean = false;
  tax: TaxDto;
  taxTypes: TaxTypeDto[] = [];

  @Output() fromSave: EventEmitter<any> = new EventEmitter<any>();

  constructor(
    _router: Router,
    injector: Injector,
    private _taxService: TaxServiceProxy,
    private route: ActivatedRoute
  ) {
      super(injector);
      this.router = _router;
   }

  ngOnInit() {
    this.loadData();
    this.getTaxTypes();
  }

  loadData(): void {
    let id = this.route.snapshot.params['id'];
    this._taxService.get(id)
    .subscribe((result: TaxDto) => {
      this.tax = result;
    })
  }

  getTaxTypes(): void {
    this._taxService.getTaxTypes()
    .subscribe((result: ListResultDtoOfTaxTypeDto) => {
        this.taxTypes = result.items;
    });
  }

}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:4)

由于您首先异步加载数据tax属性为undefined。当角度执行更改检测时,它会尝试从[(ngModel)]="tax.taxTypeId"绑定中获取值,因此您会收到错误。

有很多方法可以解决这个问题:

1)安全导航操作员

[ngModel]="tax?.taxTypeId" (ngModelChange)="tax.taxTypeId && tax.taxTypeId = $event"

2)使用预定义值

初始化属性
tax: TaxDto = new TaxDto();

3)在*ngIf="tax"

中换行模板
<select *ngIf="tax" id="taxTypeId" name="TaxTypeId" [(ngModel)]="tax.taxTypeId" ...>
   <option *ngFor="let tt of taxTypes" value={{tt.id}}>{{tt.name}}</option>
</select>