[英]angular 2 loads component too early
我有一个角2,它的构建方式如下
app.component-有多个路由-其中一个是some-data-component,这不是首先显示的默认路由。
some-data-component-有一个列表,您可以在其中选择一个项目-选中该项目后,我想在数据详细信息组件中显示所选项目。
事实是,数据详细组件正在应用程序的开头加载-我从html中收到以下错误
无法读取未定义的属性“学生”
这是有道理的,因为我还没有选择一个项目,所以它应该是未定义的
有没有办法让我构建我的应用程序,以便除非显示它们,否则不会构建其他组件?
这是我的代码:
应用组件
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']);
}
}
某些数据成分
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>
您可以使用Elvis运算符:
<tr *ngFor="let student of route?.students" ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.