2017-10-07 91 views
1

當我處理不在基類和基類中的繼承類型的成員時,Visual Studio代碼(1.17.0)在Angular模板中生成錯誤在組件上聲明。
在下面的代碼中,QuestionBase上顯然不存在maxLength,但我該如何處理?標識符'n'未定義,'object'不包含此類成員

[角度]標識符'maxLength'未定義。 'QuestionBase' 並不 沒有包含這樣的成員

export class QuestionBase { 
 
    id: number; 
 
    order: number; 
 
} 
 

 
export class TextQuestion extends QuestionBase { 
 
    maxLength: number 
 
}

在組件的問題被聲明爲QuestionBase,以便它可以成爲任何類型的問題

@Import question: QuestionBase

現在,在HTML模板我ADDRES MaxLength屬性:

<input type="text" class="form-control" id="maxLength" [(ngModel)]="question.maxLength" name="maxLength" /> 

回答

1

嘗試這樣的:

QuestionBase.ts

export class QuestionBase { 
    id: number; 
    order: number; 
} 

export class TextQuestion extends QuestionBase { 
    maxLength: number 
} 

component.ts

import { QuestionBase } from './'; 

export class Component { 

    private question: QuestionBase = new QuestionBase(); 

    constructor() { } 
} 

component.html

<input type="text" class="form-control" id="maxLength" [(ngModel)]="question.maxLength" name="maxLength" /> 
+0

Chandru您好,感謝。這工作(我的代碼也執行和工作),但仍然intellisense給出提到的錯誤。 –

+0

您還沒有聲明基於QuestionBase Schema的問題對象,這是您所犯的錯誤。 – Chandru

0

我已經通過創建eacht questiontype一個單獨的組件解決了這個問題。在每個控制器上,您可以在@Input()處指定questiontype。

<div [ngSwitch]="question.type"> 
    <app-text-question *ngSwitchCase="'text'" [question]="question"></app-text-question> 
    <app-checkbox-question *ngSwitchCase="'checkbox'" [question]="question"></app-checkbox-question> 
</div> 

TextQuestion

import { Component, OnInit, Input } from '@angular/core'; 
import { TextQuestion } from '../../_model/text-question'; 
@Component({ 
    selector: 'app-text-question', 
    templateUrl: './text-question.component.html', 
    styleUrls: ['./text-question.component.css'] 
}) 
export class TextQuestionComponent implements OnInit { 
@Input() question: TextQuestion ; 

constructor() { 
} 

ngOnInit() { 

而同爲CheckboxQuestion:

import { Component, OnInit, Input } from '@angular/core'; 
import { CheckboxQuestion } from '../../_model/checkbox-question'; 

@Component({ 
    selector: 'app-checkbox-question', 
    templateUrl: './checkbox-question.component.html', 
    styleUrls: ['./checkbox-question.component.css'] 
}) 
export class CheckboxQuestionComponent implements OnInit { 
@Input() question: CheckboxQuestion 
    constructor() { } 

    ngOnInit() { 
    } 

}