【发布时间】:2017-08-16 05:43:36
【问题描述】:
我有这样的 html 结构:
Comp1 和 Comp2 所在的父组件:
现在在 comp1 我有一些元素,如果它发生变化,那么我必须在 comp2 中反映值,但它们之间没有任何联系。
比较1:
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 它不会改变我可以得到任何触发器来知道值是否改变所以我在那里调用函数
【问题讨论】:
-
仅供参考。我删除了 PHP 标记,因为这个问题与 PHP 没有任何关系。
-
如果组件是父子关系,则使用EventEmitters,如果不使用服务在两者之间传递数据。angular.io/guide/component-interaction
-
我赞同@SimonBriggs 所说的话。您需要使用他提供的链接中给出的共享服务/
标签: javascript angular