Reputation: 402
I have a trigger directive:
@Directive({
selector: '[trigger]'
})
export class trigger {
constructor(private svc: toggleService) {}
@HostListener('click') onToggle() {
this.svc.toggle();
}
}
I also have a target directive:
@Directive({
selector: '[target]'
})
export class target {
constructor(private svc: toggleService) {}
ngOnInit() {
this.svc.onToggle.subscribe(
(toggleState: boolean) => {
this.toggleState = toggleState
}
}
}
They communicate between them via a service. The communication works fine - the target is successfully receiving a boolean state from the trigger.
<component-one>
<button trigger></button>
</component-one>
<component-two>
<div target></div>
</component-two>
If I console log within the target, I get the correct toggleState. But how do I make the toggleState available within component-two?
Upvotes: 2
Views: 704
Reputation: 910
You will have to use @output in directive like this
@Output() valueChange = new EventEmitter()
and in the function use
(toggleState: boolean) => {
this.toggleState = toggleState
this.valueChange.emit(toggleState)
}
in the button you will have to use
<div trigger (valueChange)="triggerChange($event)"></div>
than you can will get the value in triggerChange function which you can send to the second component using @input property
Or simply you can use service as described in the comments
Upvotes: 3