[英]How to call other component function from different component?
我有这样的html结构:
Comp1
和Comp2
所在的父组件:
现在在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
做到这一点,有两种方法可以实现这一目标,
使用angular service
在两个组件之间传递数据
使用Event Emitters
在组件之间传递值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.