标识符'n'未定义,'object'不包含此类成员

时间:2017-10-07 07:19:26

标签: angular templates visual-studio-code

当我从不在基类上的继承类型寻址成员并且在组件上声明基类时,Visual Studio代码(1.17.0)在Angular模板中生成错误。
在下面的代码中,maxLength上显然不存在QuestionBase,但我该怎么做呢?

  

[Angular]标识符'maxLength'未定义。 'QuestionBase'确实如此   不包含这样的成员

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

export class TextQuestion extends QuestionBase {
  maxLength: number
}

关于组件问题被声明为QuestionBase,因此它可以成为任何类型的问题

@Import question: QuestionBase

现在在html模板中我添加了maxLength属性:

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

2 个答案:

答案 0 :(得分:3)

试试这样:

<强> 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" />

答案 1 :(得分:1)

我通过为每个问题类型创建一个单独的组件来解决问题。然后,在每个控制器上,您可以在@Input()处指定问题类型。

<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() {
  }

}