javascript - 如何从不同的组件调用其他组件功能?

标签 javascript angular

我有这样的 html 结构:

Comp1Comp2 所在的父组件:

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

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

最佳答案

不能那样做,有两种可能的方法可以做到这一点,

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

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

关于javascript - 如何从不同的组件调用其他组件功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705864/

相关文章:

javascript - 在 D3 中指定可缩放热图的 View

javascript - 在 Google Maps API V3 上添加地理编码 JSON 响应回调的方法

angular - webpack- Angular : bundle includes entire node_modules of library

angular - 为什么 Angular 2 有模板的 JiT 编译?

Angular 2 标记 - 如果字符串为空,则显示其他内容

javascript - 寻找实现 AJAX TreeGrid 的最佳解决方案

javascript - JS ProgressEvent 仅在完成时触发

javascript - OpenLayers 3点文本zIndex

javascript - Angular 4 : reactive form control is stuck in pending state with a custom async validator

angular - 当解析在 Angular 5 中没有返回数据时停止路由更改