2017-11-11 81 views
2

我有一個細節形成應該從列表表單中選擇時加載一個記錄的細節。當細節形成加載時,它應該顯示所選記錄的詳細信息。在我的情況下,給出了詳細的比較正常的,但它在控制檯上顯示標題錯誤,導致應用程序崩潰。類型錯誤:無法在Object.View_FullEditTaxComponent_0._co讀取未定義的屬性「taxTypeId」 [如updateDirectives]

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

所選的選項應該是其值等於'tax.taxTypeId'的選項,但是'tax'未初始化,因此未定義,因此無法讀取'tax.taxTypeId'的值。初始化'this.tax'。 –

回答

3

由於您正在異步加載數據,因此tax屬性最初爲undefined。而當角度進行改變檢測它正試圖從[(ngModel)]="tax.taxTypeId"結合獲得價值,因此,你得到的錯誤。

有許多辦法來解決這個問題:

1)安全導航操作

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

2)*ngIf="tax"

與預定義的值初始化屬性

tax: TaxDto = new TaxDto(); 

3)總結模板

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

非常感謝。我初始化「稅」,它的工作。 –

相關問題