按照标题,我试图将循环中的当前值绑定到组件变量,这样当按下循环ui外的按钮时,我可以将它传递给另一个函数。 (基本上我在循环外面有一个可以执行功能的菜单。)
我尝试了几种不同的方法,最新的(改变)设置变量,但它似乎不起作用。
查看组件代码
<ion-slides pager="false">
<ion-slide *ngFor="let year of years | async; let i = index; let first = first; let last = last;" value="year" (change)="currentYear = years[i]">
<ion-row>
<ion-col>
<ion-icon *ngIf="!first" name="arrow-back" (tap)="slidePrev(i)"></ion-icon>
Year {{ year.year }}
<ion-icon *ngIf="!last" name="arrow-forward" (tap)="slideNext(i)"></ion-icon>
</ion-col>
</ion-row>
<ion-row>
<ion-col>
<div *ngIf="year.semesters.length === 0">
<p>Looks like you haven't added a semester yet</p>
<button (tap)="addSemester(year)">
<ion-icon name="add-circle"></ion-icon>
</button>
</div>
<div *ngIf="year.semesters.length > 0">
<ion-segment [(ngModel)]="selectedSemester">
<ion-segment-button *ngFor="let sem of year.semesters" value="{{ sem.yearId + '_' + sem.semester }}">
Semester {{ sem.semester }}
</ion-segment-button>
<ion-segment-button (click)="addSemester(year)" *ngIf="year.semesters.length < 4">
Add Semester
</ion-segment-button>
</ion-segment>
</div>
</ion-col>
</ion-row>
</ion-slide>
</ion-slides>
组件代码
currentYear: any;
this.years = this.gradesProvider.getYears(this.userId).snapshotChanges()
.map(years => {
return years.map(year => {
const data = year.payload.doc.data();
const id = year.payload.doc.id;
return this.gradesProvider.getSemesters(id).valueChanges()
.map(semesters => Object.assign({}, {id, ...data, semesters}));
});
}).mergeMap(observables => combineLatest(observables))
其他功能
slideNext() {
this.slides.lockSwipes(false);
this.selectedSemester = null;
this.slides.slideNext();
this.slides.lockSwipes(true);
}
slidePrev() {
this.slides.lockSwipes(false);
this.selectedSemester = null;
this.slides.slidePrev();
this.slides.lockSwipes(true);
}
答案 0 :(得分:1)
您可以在observable上使用currentYear
运算符设置do()
的初始值。
currentYear: any;
this.years = this.gradesProvider.getYears(this.userId).snapshotChanges()
.map(years => {
return years.map(year => {
const data = year.payload.doc.data();
const id = year.payload.doc.id;
return this.gradesProvider.getSemesters(id).valueChanges()
.map(semesters => Object.assign({}, {id, ...data, semesters}));
});
})
.mergeMap(observables => combineLatest(observables))
.do((years)=> {
if(!this.currentYear) {
this.currentYear = years[0];
}
});
这会将第一个元素分配给currentYear
一次。之后,您可以在用户点击按钮时更改currentYear
的值。
您可能希望在模板中使用<div *ngIf="currentYear">
,其中代码依赖变量currentYear
来获取值,因为它可能没有立即生成值。