繁体   English   中英

如何从不同的组件调用其他组件函数?

[英]How to call other component function from different component?

我有这样的html结构:

Comp1Comp2所在的父组件:

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

Comp1:

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它不会改变,我也可以得到任何触发器来知道值是否改变,所以我在那里调用函数

cannot做到这一点,有两种方法可以实现这一目标,

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

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

您可以从其他组件中调用另一个组件的方法,但是如果它们具有父子关系或Shared Services或使用ngrx redux pattern诸如Event Emitters类的一些调整就不会更新调用组件的值。

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

组件1

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

组成部分2

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

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

对于事件发射器,请单击此链接

对于共享服务,请点击此链接

对于ngrx,请点击此链接

暂无
暂无

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

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