【问题标题】:How to call other component function from different component?如何从不同的组件调用其他组件功能?
【发布时间】:2017-08-16 05:43:36
【问题描述】:

我有这样的 html 结构:

Comp1Comp2 所在的父组件:

现在在 comp1 我有一些元素,如果它发生变化,那么我必须在 comp2 中反映值,但它们之间没有任何联系。

比较1:

import { Component } from '@angular/core';

import { Comp2Component } from 'comp2.component';

@Component({
  selector: 'comp1',
  templateUrl: './comp1.html'
})
export class Comp1Component {

    sortBy(value)
    {
        this.FeedSortBy = value;
        this.SortByLabel = this.SortByLabelList[value];
        Comp2Component.filterActivities();
    }
}

Comp2

import { Component } from '@angular/core';
    @Component({
      selector: 'comp2',
      templateUrl: './comp2.html'
    })
    export class Comp2Component {

     filterActivities()
     {
         //call this function on comp1 sort function call so it will update value of comp2
     }

  }

根据 Rahul 和 Sajit 的回答,我尝试使用 EventEmitter 并将我的结构更改为父子:

在我的父组件中我使用:

import { Component,EventEmitter, Input, Output, OnInit } from '@angular/core';

import { FeedsComponent } from '../feeds/feeds.component';

@Component({
  selector: 'my-desk',
  styleUrls: ['../../assets/css/style.min.css'],
  templateUrl: './my-desk.component.html'
})
export class MyDeskComponent {

    @Output() FeedSortBy = new EventEmitter<string>();
    sortBy(value)
    {
        this.FeedSortBy.emit(value);
    }
}

在我的子组件中我使用:

import { Component, OnInit, Input, Output } from '@angular/core';

import { DataService } from '../data.service';

declare var $: any;

@Component({
  selector: 'feeds',
  styleUrls: ['../../assets/css/style.min.css'],
  templateUrl: './feeds.component.html'
})
export class FeedsComponent {
    constructor(private dataService:DataService)
    {

    }
    @Input() FeedSortBy:number = 2;
}

子组件 HTML:

{{FeedSortBy}}

但它总是输出 2 它不会改变我可以得到任何触发器来知道值是否改变所以我在那里调用函数

【问题讨论】:

  • 仅供参考。我删除了 PHP 标记,因为这个问题与 PHP 没有任何关系。
  • 如果组件是父子关系,则使用EventEmitters,如果不使用服务在两者之间传递数据。angular.io/guide/component-interaction
  • 我赞同@SimonBriggs 所说的话。您需要使用他提供的链接中给出的共享服务/

标签: javascript angular


【解决方案1】:

cannot这样做,有两种可能的方法可以实现这一目标,

  1. 使用angular service在两个组件之间传递数据

  2. 使用 Event Emitters 在组件之间传递值。

【讨论】:

【解决方案2】:

您可以从不同的组件调用另一个组件的方法,但如果不进行一些调整,它不会更新调用组件的值 Event Emitters 如果他们有父子关系或Shared Services 或使用ngrx redux pattern

如何调用不同的组件方法就像

组件1

  test(){
    console.log("Test");
  }

组件 2

  working(){
    let component = new Component1();
    component.test();
  }

现在要更新组件 2 中的值,您可能必须使用上述任何一种。

对于事件发射器,请关注link

对于共享服务,请关注link

对于ngrx,请关注link

【讨论】:

  • 嗨,我用 EventEmitter 的例子更新了我的问题,但仍然没有得到任何值,有没有办法在值更新时触发?
  • @MohitBumb 这不是使用事件发射器的正确方法,请查看上面的链接和相应的 git 代码
  • 一个重要的注意事项,即使你使用正确的语法,这些组件是否有父子关系,我不知道它们有,你可能需要使用共享服务或 ngrx @MohitBumb
  • 感谢 mate 提供的链接和示例现在可以正常工作了 :)
最近更新 更多