如何使用事件发射器触发 child 和 parent 组件中的函数?
How do I trigger functions in both the child AND parent component using Event Emitters?
我有一个 parent 和 child 组件,我希望 parent 能够触发 child 中的函数,同时还允许 child 触发 parent 中的一个。下面是我为 child 所做的,以触发 parent 中的函数:
Child
@Output() callParentFunction = new EventEmitter<any>();
...
this.callParentFunction.emit();
Parent
template: `
<child-component
(callParentFunction)="parentfunction($event)"
>
</child-component>
`
这可以触发 parentfunction
,但我该如何从另一个方向开始?我需要使用 parent.
中的事件发射器触发 child 函数
这样试试
parent
template: `
<child-component
[events]="eventsSubject.asObservable()"
>
</child-component>
`
private eventsSubject: Subject<void> = new Subject<void>();
anyfunction(){
this.eventsSubject.next()
}
child
@Input() events: Observable<void>;
ngOnInit() {
this.events.subscribe(() =>
//do something
);
}
您可以使用 ngOnChanges()
。所以你可以处理 .
A callback method that is invoked immediately after the default change
detector has checked data-bound properties if at least one has
changed, and before the view and content children are checked.
@Component({selector: 'child', template: `...`})
class ChildComponent implements OnChanges {
// TODO(issue/24571): remove '!'.
@Input()
prop: number;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
然后从父组件更新一些对象foo
然后ngOnChanges
方法将被触发:
<child-component
[events]="eventsSubject.asObservable()"
[prop] = "foo"
>
</child-component>
我有一个 parent 和 child 组件,我希望 parent 能够触发 child 中的函数,同时还允许 child 触发 parent 中的一个。下面是我为 child 所做的,以触发 parent 中的函数:
Child
@Output() callParentFunction = new EventEmitter<any>();
...
this.callParentFunction.emit();
Parent
template: `
<child-component
(callParentFunction)="parentfunction($event)"
>
</child-component>
`
这可以触发 parentfunction
,但我该如何从另一个方向开始?我需要使用 parent.
这样试试
parent
template: `
<child-component
[events]="eventsSubject.asObservable()"
>
</child-component>
`
private eventsSubject: Subject<void> = new Subject<void>();
anyfunction(){
this.eventsSubject.next()
}
child
@Input() events: Observable<void>;
ngOnInit() {
this.events.subscribe(() =>
//do something
);
}
您可以使用 ngOnChanges()
。所以你可以处理 .
A callback method that is invoked immediately after the default change detector has checked data-bound properties if at least one has changed, and before the view and content children are checked.
@Component({selector: 'child', template: `...`})
class ChildComponent implements OnChanges {
// TODO(issue/24571): remove '!'.
@Input()
prop: number;
ngOnChanges(changes: SimpleChanges) {
// changes.prop contains the old and the new value...
}
}
然后从父组件更新一些对象foo
然后ngOnChanges
方法将被触发:
<child-component
[events]="eventsSubject.asObservable()"
[prop] = "foo"
>
</child-component>