【发布时间】:2017-10-30 09:23:21
【问题描述】:
在父组件(ParentComponent)上加载所有父数据的onInit方法。现在,如果我单击单个父级,它会通过将 parentId 从 ParentComponent 传递给 ParentDetailComponent 来触发子视图,并且 ParentDetailComponent 调用 ParentDetailService 并获取 IParent 对象。现在我尝试使用 *ngIf 来显示 ParentDetailComponent 模板,但它没有触发。如何触发子视图?
子模板:
<div *ngIf="DetailIsVisible" id="detailModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Parent Detail</h4>
</div>
<div class="modal-body">
<div *ngIf="parent">
<h2>{{parent.name}} details!</h2>
<div><label>id: </label>{{parent.Id}}</div>
<div>
<label>name: </label>
<label>{{parent.name}}</label>
</div>
<div>
<label>Education: </label>
<label>{{parent.education}}</label>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" (click)="hideDetail()">Close</button>
</div>
</div>
</div>
子组件:
@Component({
selector: 'app-parent-detail',
templateUrl: './child.component.html',
providers: [ParentDetailService]
})
export class ParentDetailComponent{
parentId: string;
parent: IParent;
public DetailIsVisible: boolean;
constructor(private _parentDetailService: ParentDetailService) {
}
show(parentId: string) {
this.serviceDetail = serviceId;
this._parentDetailService.getParentServiceDetail(this.parentId).subscribe(parent => {
this.parent = parent[0];
console.log(this.parent);
});
}
hideDetail() {
this.DetailIsVisible = false;
}
}
父模板:
div class="container">
<div class="row">
<div class="col-sm-4" *ngFor="let parent of parents" (click)="selectedServiceDetail(parent.Id)" data-target="#detailModal">
<div class="panel panel-primary" >
<div class="panel-heading">{{parent.Id}}</div>
<div class="panel-body"><img [src]="parent.thumbnailpath"
class="img-responsive" style="width:100%; height: 200px" [title] = 'parent.name' alt="Image"></div>
<div class="panel-footer">{{parent.name}}</div>
</div>
</div>
</div>
父组件:
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
providers: [ParentDetailService]
})
export class ParentComponent implements OnInit {
/**all rest api and assign to array of catalog*/
public parents: IParent[];
public DetailIsVisible: boolean;
@ViewChild(ParentDetailComponent) detailModal: ParentDetailComponent;
constructor(private _parentService: ParentService) {
}
ngOnInit(): void {
this._parentService.getParents()
.subscribe(
parents => this.parents = parents
);
this.detailModal.DetailIsVisible = false;
}
public selectedServiceDetail(parentId): void {
this.detailModal.DetailIsVisible = true;
this.detailModal.show(parentId); ---> this triggers ChildComponent method to fetch parent detail service
}
【问题讨论】:
-
你可以在 andgular2 中使用@Output eventemitter 你可以从这个问题的答案中找到帮助stackoverflow.com/questions/36076700/…
标签: angular angular2-services angular2-components