问题描述
我有一个Submit button in the parent component namely
personDetails .
personDetails has many
person`组件.每当我单击提交"按钮时,我都想在子组件中调用一个方法.
I have a Submitbutton in the parent component namely
personDetails.
personDetailshas many
person` components. Whenever I click on the Submit button, I want to call a method in child component.
如何使用@Output
从父组件向子组件发出事件?
How can I emit an event from a parent to a child component using @Output
?
从孩子到父母都很容易做到.我想访问子组件的值,因此需要从父组件向子组件发出一个事件.
Its easy to do it from the child to the parent. I want to access a value of the child component, hence I need to emit an event from parent to child.
推荐答案
您可以创建一项在父组件和子组件之间共享的服务,您可以在其中定义Observable
,以便可以从中订阅该Observable
子级,并在您从父级那里获得一些价值时执行一些操作.
You can create one service which is shared between your parent and child component in which you can define Observable
so that you can subscribe to that Observable
from child and perform some action when you receive some value from parent.
//common.service.ts
import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class CommonService {
private notify = new Subject<any>();
/**
* Observable string streams
*/
notifyObservable$ = this.notify.asObservable();
constructor(){}
public notifyOther(data: any) {
if (data) {
this.notify.next(data);
}
}
}
//parent.component.ts
//parent.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CommonService } from './common.service';
@Component({
selector : 'parent',
templateUrl : './parent.html'
})
export class ParentComponent implements OnInit, OnDestroy {
constructor( private commonService: CommonService ){
}
ngOnInit() {
this.commonService.notifyOther({option: 'call_child', value: 'From child'});
}
}
//child.component.ts
//child.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { CommonService } from './common.service';
@Component({
selector : 'child',
templateUrl : './child.html'
})
export class ChildComponent implements OnInit, OnDestroy {
private subscription: Subscription;
constructor( private commonService: CommonService ){
}
ngOnInit() {
this.subscription = this.commonService.notifyObservable$.subscribe((res) => {
if (res.hasOwnProperty('option') && res.option === 'call_child') {
console.log(res.value);
// perform your other action from here
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
这篇关于将事件从父母传给孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!