简体   繁体   English

从一个组件通信到另一个Angular 5

[英]Communicating from one component to another Angular 5

I have two components a navigation component and a detail component. 我有两个组件:导航组件和详细信息组件。 In my navigation component I have a few options or items the user can select. 在我的导航组件中,我有几个选项或用户可以选择的项目。 When a user selects one I am trying to update a masonry grid in the detail. 当用户选择一个时,我正在尝试更新详细的砌体网格。 I am able to update the masonry grid but I need to call a method prepended(). 我能够更新砌体网格,但是我需要调用方法prepended()。 For example: 例如:

Code in detail component: 详细代码组件:

  import Masonry from 'masonry-layout';

  // on ngOnInit
  let grid = document.querySelector('.grid');

  let msnry = new Masonry( grid, {
    itemSelector: '.grid-item',
  });

I need to call the following from my naviagtion component: 我需要从我的导航组件中调用以下命令:

msnry.prepended();

How do I call msnry.prepended() from another component? 如何从另一个组件调用msnry.prepended()? Any assistance would be greatly appreciated. 任何帮助将不胜感激。

If they have a parent child relationship then you can use the template reference variable technique to call a method of the child component from the parent component. 如果它们具有父子关系,则可以使用模板引用变量技术从父组件中调用子组件的方法。 For example, assume the following div is you navigation component template, 例如,假设以下div是导航组件模板,

<div>
    <detail-component #detailComponent></detail-component>
    <button (click)="detailComponent.sayHello()"/>
</div>

Considering your detail component has a method named sayHello() . 考虑到您的详细信息组件有一个名为sayHello()的方法。 The button on the navigation component will call that method when clicked. 单击导航组件上的按钮将调用该方法。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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