大菜鸟,第一个问题。课程项目“测验应用程序”显示一个又一个问题,并在最后显示结果。我想通过计算结果页面上“正确”类的元素数量来添加正确答案的数量。如果需要更多信息或任何其他信息,请告诉我!
到目前为止尝试过:
-test1:“计数”它们并显示得很好,问题是它执行计数时有 0,因为它们还没有创建。
-test2:在使用生命周期钩子 ngAfterViewChecked() 创建它们后对它们进行计数。Console.log 显示正确的数字;但我不知道如何将其转移到模板中。在组件中声明一个变量,让生命周期钩子的函数更改变量,并将变量包含在模板中;但它只是不像 test1() 那样出现在页面上。
结果.component.html:
<div class="results">
<mat-card>
<mat-card-title>
<h1><u>Results</u></h1>
</mat-card-title>
<br/>
<div
*ngFor="let a of answers.values"
class="answer"
[ngClass]="{ correct: a.correct }"
>
{{a.value}}
<br/>
<br/>
</div>
<button routerLink="/">Home</button>
</mat-card>
{{test1()}}
{{test2}}
</div>
结果.component.ts:
import { Component, Input } from '@angular/core';
import { AsyncValidatorFn } from '@angular/forms';
import { Answers } from '../quiz.model';
@Component({
selector: 'app-results',
templateUrl: './results.component.html',
styleUrls: ['./results.component.scss']
})
export class ResultsComponent {
@Input() answers: Answers;
test1() {
return document.querySelectorAll(".correct").length;
}
public test2: number;
ngAfterViewChecked(){
console.log(document.querySelectorAll(".correct").length);
this.test2 = document.querySelectorAll(".correct").length;
}
}