[英]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.