我有这样的 html 结构:
Comp1
和 Comp2
所在的父组件:
现在在 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 它不会改变我是否可以得到任何触发器来知道值是否改变所以我在那里调用函数
最佳答案
你不能
那样做,有两种可能的方法可以做到这一点,
使用
angular service
在两个组件之间传递数据使用
Event Emitters
在组件之间传递值。
关于javascript - 如何从不同的组件调用其他组件功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705864/