Update: I finally figured it out. After moving all the html from index.html
to app.component.ts
, everything started working perfectly. The method described below is the correct one.
I've been facing an issue where I have a ParentComponent that retrieves data from a service and displays it in a sidebar. When clicking on an item in the sidebar, it should display details about that parent component in the main section of the page. Since this requires using two different templates, my solution was to establish a parent-child relationship with the sidebar as the parent and the detail section as the child, passing the necessary data to the child for display. Does this approach seem appropriate? Is there a better way to tackle this problem? I've experimented with various methods, but they all seem outdated as they rely on directives
which are no longer supported.
Update: This question differs from the other one because the answer mentions directives
which were phased out in the rc6 release of angular2. This question pertains to post-rc6 changes.
Additional Code snippet:
index.html:
<header>
<div class="content">This is a header</div>
</header>
<div class="container">
<div class="sidebar">
<div class="content">
<parent-items></parent-items>
</div>
</div>
<div class="main-content">
<div class="content">
<my-app>Loading...</my-app>
<child-cmp [id]="selectedItem.id"></child-cmp>
</div>
</div>
<div class="clearfix"></div>
</div>
child-cmp.ts:
@Component({
selector: 'child-cmp',
})
export class ChildComponent {
@Input() set id(n) {
this.getData(n)
}
getData(id: number): void {
console.log('triggered');
};
}
parent.ts:
@Component({
moduleId: module.id,
selector: 'parent-items',
templateUrl: `<ul class="items">
<li *ngFor="let item of items"
(click)="selectedItem = item"
[class.selected]="item === selectedItem">{{item.name}}</li>
</ul>`,
})
export class ItemsComponent implements OnInit {
items: Item[];
selectedItem: Item;
constructor(private itemService: ItemService) {};
getItems(): void {
this.itemService
.getItems()
.then(items => this.items = items);
}
ngOnInit(): void {
this.getItems();
}
}