我得到上面的错误信息,但不明白为什么因为我能看到的所有内容都已定义。
继承人我的HTML:
显然,错误发生在第1行
<div *ngIf="pager.index < quiz.questions.length">
<h5 class="flow-text"><span [innerHTML]="quiz.questions[pager.index].text"></span></h5>
<br>
<div class="row text-left">
<div class="col s12 m12" *ngFor="let answer of quiz.questions[pager.index].answers">
<div class="answer">
<input type="checkbox" [checked]="answer.selected" (change)="onSelect(answer);"/><label class="black-text flow-text"> {{answer.text}} </label>
</div>
</div>
</div>
<footer class="row">
<div class="col s6 m6"></div>
<div class="col s6 m6">
<div *ngIf="pager.index < quiz.questions.length - 1">
<button id="nextButton" class="btn-flat black-text right flow-text" (click)="goTo(pager.index + 1);">Next</button>
</div>
<div *ngIf="pager.index == quiz.questions.length - 1">
<button id="nextButton" class="btn-flat black-text right flow-text" (click)="goTo(pager.index + 1);">Finish</button>
</div>
</div>
</footer>
</div>
<div *ngIf="pager.index == quiz.questions.length">
{{ selections }}
</div>
这是component.ts
import { Component, OnInit, EventEmitter } from '@angular/core';
import { QuizService } from '../services/quiz.service';
import { Answer, Question, Quiz } from '../models/index';
import {MaterializeAction} from "angular2-materialize";
@Component({
selector: 'app-quiz',
templateUrl: './quiz.component.html',
styleUrls: ['./quiz.component.sass'],
providers: [QuizService]
})
export class QuizComponent implements OnInit {
quiz: Quiz;
pager = {
index: 0,
size: 1,
count: 1
};
selections: [string]
constructor(private quizService: QuizService) { }
ngOnInit() {
this.loadQuiz()
}
loadQuiz() {
this.quizService.get().subscribe(res => {
this.quiz = new Quiz(res);
this.pager.count = this.quiz.questions.length;
});
}
goTo(index: number) {
if (index >= 0 ) {
this.pager.index = index;
}
}
onSelect(answer: Answer) {
if (answer.selected = true) {
this.selections.splice(this.selections.indexOf(answer.text), 1);
} else {
this.selections.push(answer.text);
}
answer.selected = !answer.selected
}
}
除了我在另一个问题中提出的复选框之外,我不明白为什么它会发生,尽管编译代码的错误仍在运行并且应该运行。
答案 0 :(得分:3)
在这种情况下你应该使用安全导航操作符
*ngIf="pager.index < quiz?.questions?.length"
和
*ngIf="pager.index == quiz?.questions?.length"
答案 1 :(得分:0)
似乎quiz
变量为undefined
,将其定义为quiz: Quiz={}