Reputation: 137
Sorry, I can't post all the code here. But, if you could give me some hint as to what needs to be done, I'd appreciate it.
Let me try to explain my predicament.
So, this is the code snippet I've been trying to use ngFor
and ngIf
on:
<li class="list-group-item" *ngFor="let option of question.options">
<div class="form-check lead">
<input
class="form-check-input"
type="checkbox"
value=""
id="{{ option.id }}"
[(ngModel)]="option.selected"
(change)="onSelect(question, option)"
disabled="disabled"
/>
<label
class="form-check-label d-block fw-normal"
[attr.for]="option.id"
>
{{ option.name }}
<ng-container *ngFor="let obj of response"
><fa-icon
*ngIf="
obj.qId == option.questionId && obj.correct.includes(option.id)
"
[icon]="faCheck"
></fa-icon
></ng-container>
</label>
<div>
<img
src="{{ option.image }}"
alt=""
onerror="this.onerror=null; this.remove();"
width="55"
height="55"
/>
</div>
</div>
</li>
Before this code there is this element,
<div class="d-flex flex-column bg-white px-5" *ngFor="let question of filteredQuestions" style="white-space: pre-line">
filteredQuestions()
loads the array of objects in which there are questions and inside of a question, there is array of options
.
Now, what I want is to display the check
icon right next to the correct option.
This is the response
array:
response = [
{ qId: '60e57c069107a038085ae3a1', correct: [1001, 1002] },
{ qId: '60e57cc09107a038085ae3a2', correct: [1002] },
{ qId: '60e57d289107a038085ae3a3', correct: [1003] },
{ qId: '60e57d9e9107a038085ae3a4', correct: [1001, 1002, 1003] },
{ qId: '60e57e7c9107a038085ae3a5', correct: [1004] }];
This is the overall structure for the options:
[{id: number;
questionId: number;
name: string;
image: string;
selected: boolean;}]
I've tried to use the ngFor
on different tags but with no luck. Right now, there are no check icons based on the if condition on the fa-icon tag.
And when I remove the ngIf
from the fa-icon tag in this case, the checks just print multiple times. Where can I apply the tag so that the element won't repeat and I can get my desired output?
Upvotes: 4
Views: 1329
Reputation: 9923
The problem is that your option.id
is not number, so this obj.correct.includes(option.id)
was not satisfied and does not meet your *ngIf
condition in below line of code:
<fa-icon *ngIf="obj.qId == option.questionId && obj.correct.includes(+option.id)" [icon]="faCheck"></fa-icon>
So easy way to solve the problem is that put +
next to the option.id
:
obj.correct.includes(+option.id)
<ng-container *ngFor="let obj of response">
<fa-icon *ngIf="obj.qId == option.questionId && obj.correct.includes(+option.id)" [icon]="faCheck"></fa-icon>
</ng-container>
Here is working sample
And the result:
Upvotes: 2