Angular 6 + 为无序列表中的嵌套 ngFor 设置活动
Angular 6 + set active for nested ngFor in unordered list
我将 *ngFor 嵌套在一个无序列表中,例如:
<div *ngFor="let q of questions; let i = index;">
<label>{{ q.questionDesc }}</label>
<ul class="list-group">
<li class="list-group-item list-group-item-action" [class.active]="active === j" (click)="onClick(j)" *ngFor="let c of q.choices; let j = index;">
{{ c }}
</li>
</ul>
<hr/>
我的打字稿代码:
active: number;
onClick(index: number) {
this.active = index;
}
当我在内部 *ngFor 中 select 一个 "q.choices" 项目 (c) 时,同一项目在所有列表中得到 selected。我只想 selected 一个项目。我可能需要为每个选择分配一个唯一的 ID,但不确定如何完成此操作。
有什么想法吗?
您可以尝试这种方法,它将活动选择存储在 questions
数组的每个 question
项中:
questions = [
{
questionDesc: "description here",
choices: ["choice 1", "choice 2", "...etc"],
activeChoice: -1
},
{
questionDesc: "description here",
choices: ["choice 1", "choice 2", "...etc"],
activeChoice: -1
},
// ...etc
]
onClick(questionIndex: number, choiceIndex: number) {
this.questions[questionIndex].activeChoice = choiceIndex;
}
HTML:
<div *ngFor="let q of questions; let i = index;">
<label>{{ q.questionDesc }}</label>
<ul class="list-group">
<li class="list-group-item list-group-item-action" [class.active]="questions[i].activeChoice === j" (click)="onClick(i, j)" *ngFor="let c of q.choices; let j = index;">
{{ c }}
</li>
</ul>
<hr/>
</div>
我将 *ngFor 嵌套在一个无序列表中,例如:
<div *ngFor="let q of questions; let i = index;">
<label>{{ q.questionDesc }}</label>
<ul class="list-group">
<li class="list-group-item list-group-item-action" [class.active]="active === j" (click)="onClick(j)" *ngFor="let c of q.choices; let j = index;">
{{ c }}
</li>
</ul>
<hr/>
我的打字稿代码:
active: number;
onClick(index: number) {
this.active = index;
}
当我在内部 *ngFor 中 select 一个 "q.choices" 项目 (c) 时,同一项目在所有列表中得到 selected。我只想 selected 一个项目。我可能需要为每个选择分配一个唯一的 ID,但不确定如何完成此操作。
有什么想法吗?
您可以尝试这种方法,它将活动选择存储在 questions
数组的每个 question
项中:
questions = [
{
questionDesc: "description here",
choices: ["choice 1", "choice 2", "...etc"],
activeChoice: -1
},
{
questionDesc: "description here",
choices: ["choice 1", "choice 2", "...etc"],
activeChoice: -1
},
// ...etc
]
onClick(questionIndex: number, choiceIndex: number) {
this.questions[questionIndex].activeChoice = choiceIndex;
}
HTML:
<div *ngFor="let q of questions; let i = index;">
<label>{{ q.questionDesc }}</label>
<ul class="list-group">
<li class="list-group-item list-group-item-action" [class.active]="questions[i].activeChoice === j" (click)="onClick(i, j)" *ngFor="let c of q.choices; let j = index;">
{{ c }}
</li>
</ul>
<hr/>
</div>