There are actually two challenges I face. I am looping through an array of values and need to
- set a class name depending on an observable variable from a child component.
- reevaluate the class as soon as the child variable changes.
location.component.ts
import { Component, Input } from '@angular/core';
import { BusinessLocation, SpecialDays, RegularHours } from './location';
import { DbService } from './db-service.component';
@Component({
selector: '[data-locations]',
templateUrl: 'app/location.component.html',
providers: [DbService]
})
export class LocationComponent {
locations:BusinessLocation[];
selectedLocationId:Number;
constructor(private api:DbService){}
isOpenOnDay(day):Boolean {
let _weekDay = day.getDay();
let _retour = false;
this.locations.forEach(loc => {
if ( loc.id == this.selectedLocationId && loc.regularHours.weekDay == _weekDay ) {
_retour = true;
}
});
this.locations.forEach(loc => {
if ( loc.id == this.selectedLocationId && loc.specialDays.singleDate.getDay() == _weekDay) {
_retour = true;
}
});
return _retour;
}
getLocation():Number {
return this.selectedLocationId;
}
setLocation(id):void {
this.selectedLocationId = id;
}
getLocations():void {
this.api.getLocations().subscribe(
locations => {
this.locations = locations as BusinessLocation[];
this.setLocation(this.locations[0].id);
}
);
}
}
a snippet from db-services.component.ts
getLocations():Observable<BusinessLocation[]> {
return this.http.get(this.apiUrl + '/get_locations.php')
.map(response => response.json().data as BusinessLocation[]);
}
}
it all works fine. However, here is where the challenge is. The parent component initiates the locations, but it also needs to know what location is selected right now. Here is the month.component.html
<span class="location-container" #location data-locations><span class="loading">Loading locations...</span></span>
<div *ngFor="let day of week.days" class="day" data-can-drop="day"
[class.today]="isToday(day)"
[class.in-other-month]="day.getMonth() != jsMonth"
[class.is-closed]="!isOpenAtLocation(day)">
<div class="day-marker"></div>
<span class="day-date">{{day | date:'d'}}</span>
<span *ngIf="checkMonth(day)" class="day-month">{{months[day.getMonth()]}}</span>
</div>
and a snippet from month.component.ts is
@ViewChild('location') locationComponent:LocationComponent;
isOpenAtLocation(day):Boolean {
return this.locationComponent.isOpenOnDay(day);
}
ngOnInit(): void {
this.locationComponent.getLocations();
}
The error I get is pretty straightforward and totally understandable:
Subscriber.ts:238 TypeError: Cannot read property 'forEach' of undefined
at LocationComponent.isOpenOnDay (location.component.ts:25)
at MonthComponent.isOpenAtLocation (month.component.ts:176)
And this is just about Challenge 1. The Challenge 2 has not been even addressed yet.
I just can't wrap my head around it. >_< Thanks.