使用输入/输出事件在 Angular 2 中的父组件中触发方法
Using input/output events to trigger methods in a parent component in Angular 2
子服务如何通知父组件更改?我曾经通过在子服务中$watching一个变量来在角度 1 中执行此操作。不幸的是,这不再可能。
我尝试将服务注入回组件中,但这失败了,可能是由于循环依赖关系。根据我在当前文档中可以找到的内容,我想出了以下代码:
AppComponent
|
SomeComponent
|
SomeService
应用组件
@Component({
selector: '[app-component]',
templateUrl: 'partials/app.html',
directives: [
SomeComponent
],
providers: [
SomeService
]
})
export class AppComponent {
constructor() { }
}
bootstrap(AppComponent);
一些组件
import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'
@Component({
selector: 'foo',
templateUrl: 'partials/foo.html'
})
export class SomeComponent {
constructor() {}
@Input set someEvent(value) {
console.log(value);
}
}
一些服务
import {EventEmitter, Output} from 'angular2/core'
export class CoreService {
constructor() {
this.someEvent = new EventEmitter();
}
@Output() someEvent: EventEmitter<any>;
public foo() {
this.someEvent.emit(true); // Or next(true)?
}
}
@Output
必须仅用于服务中的组件。在此级别,可以使用(...)
语法注册此事件。
从 angular.io 文档 (https://angular.io/docs/ts/latest/api/core/Output-var.html):
声明事件绑定输出属性。
当输出属性发出事件时,将调用附加到该事件的事件处理程序。
对于服务,您需要显式订阅此事件,如下所述:
import {Component, Input} from 'angular2/core'
import {SomeService} from '../services/some.service'
@Component({
selector: 'foo',
templateUrl: 'partials/foo.html'
})
export class SomeComponent {
constructor(service:CoreService) {
service.someEvent.subscribe((val) => {
console.log(value);
});
}
}
相关文章:
- react组件中的绑定方法
- Angular2将组件方法导入到另一个组件中
- 从vuejs中的组件模板访问父方法
- 在React中将方法从一个组件移动到另一个组件,并且仍然可以在原始组件中使用
- 如何从Vue.js中的子组件访问父方法
- Redux-组件不同的方法(智能/哑点/容器/演示)
- 组件之后子元素中的某个方法DidMount in parrent 元素
- bind():您正在将一个组件方法绑定到该组件.React会自动为您执行此操作
- Emberjs-如何在组件方法中获取当前路由器路径
- EmberJS - 使用几个解决方案从外部调用组件方法(呼吁讨论)
- ReactJS以正确的方式绑定组件方法
- 如何从WebSocket回调访问React中的组件方法
- Angular 1.5组件方法templateUrl+函数
- React组件方法this.state.myState从child返回后未定义
- 在React中暴露组件方法
- finddomnode(组件)方法列表
- 用Sinon存根一个React组件方法
- 在ReactJs组件方法调用之间存储变量
- 我只能在使用Angular2 Universal的客户端中运行组件方法吗
- 在 constructor() 中绑定许多 React 组件方法的上下文的正确约定是什么?