Reputation: 2002
I have an angular 2 and it's built somewhat in the following way
app.component - has several routes - one of them is some-data-component, which isn't the default route shown first.
some-data-component - has a list, where you can select an item - when it is selected I want to display the selected item in a data-details-component.
the thing is, data-detail-component is being loaded at the start of the app - and I am getting the following error from it's html
Cannot read property 'students' of undefined
this makes sense, because I haven't chosen an item yet, so it should be undefined
is there a way for me to build my app so it won't build those other components unless they are shown?
this is my code:
app.component
import { Component, OnInit } from '@angular/core';
import {Routes, Router, ROUTER_DIRECTIVES} from '@angular/router';
import { Dashboard } from './dashboard/dashboard.component';
import {SomeDataComponent} from './some-data-component/some-data-component';
@Component({
selector: 'my-app',
templateUrl: './app/components/app.component.html'
, directives: [ROUTER_DIRECTIVES]
})
@Routes([
{ path: '/somedata', component: SomeDataComponent},
{ path: '/dashboard', component: Dashboard }
])
export class AppComponent implements OnInit {
mobileView: number = 992;
toggle: boolean = false;
constructor(private router: Router) {
this.attachEvents();
}
ngOnInit() {
this.router.navigate(['/dashboard']);
}
}
some-data-component
import {SomeDataListView} from '../some-data-list-view/some-data-list-view';
import {DataDetailComponent} from '../data-detail/data-detail.component';
import {SomeService} from '../../services/some_service';
@Component({
selector: 'some-data-component',
providers: [SomeService],
templateUrl: 'app/components/some-data/some-data.html',
directives: [SomeDataListView, DataDetailComponent]
})
export class RoutesComponent {
data;
selectedData;
constructor(private someService: SomeService) {
this.data=[]
}
ngOnInit() {
this.data= this.SomeService.all();
}
selectedRouteChanged(route) {
this.selectedRoute = route;
}
}
some-data.html
<rd-widget>
<rd-widget-body classes="medium no-padding">
<div>
<img src="{{route.imgSrc}}" />
<label>Neighborhood: {{route.name}}</label>
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th class="text-center">ID</th>
<th>Neighborhood</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let student of route.students" (click)="setSelected(route)">
<td>{{student.id}}</td>
<td>{{student.neighborhood}}</td>
<td>
<span class="{{route.tooltipcls}}">
<i class="fa {{route.icon}}"></i>
</span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</rd-widget-body>
</rd-widget>
Upvotes: 0
Views: 315
Reputation: 202246
You could use the Elvis operator:
<tr *ngFor="let student of route?.students" ...
Upvotes: 1