问题描述
我在父组件中有一个提交按钮,即
personDetails.
personDetails有很多
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();
}
}
这篇关于从父级向子级发出事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!