avoliva avoliva - 1 month ago 11
TypeScript Question

Issue communicating between two components in angular2 using @Input

EDIT: Figured it out, I just moved all the html in the body of

index.html
to the
app.component.ts
template as index.html won't parse any of the template code.

My issue is that I have a ParentComponent which reads from a service, and posts the data to a sidebar. When you click an item in the sidebar it's supposed to post details about that parent in the main section of the page. I'm trying to use
@Input
to communicate between the two components but it doesn't seem to be triggering. I'm not quite sure why but I just need to knock this out because it seems like a relatively simple problem but I can't figure out a solution. Any help is appreciated.

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',
template: `<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();
}
}

Answer

<child-cmp [id]="selectedItem.id"></child-cmp> must be in ItemsComponent's template.