简体   繁体   中英

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();
  }
}

<child-cmp [id]="selectedItem.id"></child-cmp>必须在ItemsComponent的模板中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM