'Angular - *ngFor: Passing i from index in ts file
I'm trying to pass the index from a ngFor to a my ts file without any success. I actually don't know how to do that. Can someone tell me how to pass the index value from the html to the ts file? I thought using a @Input would be te solution but nothing happen... Thanks.
My HTML:
<div *ngFor="let question of questions | async; index as i">{{question.libelle}}
<div class="row text-left options">
<div class="col-md-6" *ngFor="let reponse of reponses | async">
<div class="option">
<label class="" [attr.for]="reponse.id">
<input type="checkbox" [(ngModel)]="reponse.Selected"/>
{{reponse.libelle}}
</label>
</div>
</div>
</div>
{{i}}
</div>
My TS:
@Injectable()
@Component({
selector: 'app-java',
templateUrl: './java.component.html',
styleUrls: ['./java.component.sass']
})
export class JavaComponent implements OnInit {
@Input() i : any;
questions :any = [];
reponses :any = [];
constructor(private questionnaireService: QuestionnaireService) { }
ngOnInit() {
this.questions = this.questionnaireService.getQuestion();
this.reponses = this.questionnaireService.getReponse(this.i);
}
}
Solution 1:[1]
You can achieve these with 3 steps
Keep the currentIndex in ts file
Set the currentIndex from the html
Call getter method from the *ngFor
in ts
@Injectable()
@Component({
selector: 'app-java',
templateUrl: './java.component.html',
styleUrls: ['./java.component.sass']
})
export class JavaComponent implements OnInit {
@Input() i : any;
questions :any = [];
reponses :any = [];
constructor(private questionnaireService: QuestionnaireService) { }
ngOnInit() {
this.questions = this.questionnaireService.getQuestion();
}
//Track the current Index
public currentIndex;
//Current Index Setter
setCurrentIndex(index){
this.currentIndex = index;
}
//Getter for response which will use currentIndex
get responses(){
return this.questionnaireService.getReponses(this.currentIndex)
}
}
in html
<div *ngFor="let question of questions | async; index as i">{{question.libelle}}
<div class="row text-left options" #>
{{setCurrentIndex(i)}} <-- Set the current Index -->
<div class="col-md-6" *ngFor="let reponse of responses | async">
<div class="option">
<label class="" [attr.for]="reponse.id">
<input type="checkbox" [(ngModel)]="reponse.Selected"/>
{{reponse.libelle}}
</label>
</div>
</div>
</div>
{{i}}
</div>
Note : since you are using async pipe make sure all your results are Observable.
Solution 2:[2]
normally <div *ngFor="... let ii==index"> will be enough to pass the ii, however, in my case there is a *ngIf in sub , so that messed up the count and made it undefined. I endup make the *ngIf on the top level above *ngFor.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Community |
| Solution 2 | Feng Zhang |
