I need to build custom RadioButtons. When one is selected, it calls a service who will send its identifier to all subscribed RadioButtons including the caller. If the subscribe sees that the key (instance + id) is NOT the same as itself, it will uncheck itself otherwise the matching instance + id (who is indeed the caller) will remain as checked. The service:
import { Injectable } from '@angular/core';
import { BehaviorSubject} from 'rxjs/BehaviorSubject';
import {Subject} from 'rxjs/Subject';
@Injectable()
export class RadioButtonService {
public Status_Subject: Subject<string> = new BehaviorSubject<string>('x;y');
constructor() {
}
public setRadioChecked(instance: string, id: string ) {
const key = instance + ';' + id;
this.Status_Subject.next(key);
}
}
Relevant part of the component:
export class RadioButtonComponent implements AfterViewInit, OnDestroy {
@Input() id: string;
@Input() instanceId: string;
@Input() group: string;
isdisabled = false;
ischecked = false;
subj: Subject<string>;
constructor(private radSvc: RadioButtonService) {
this.subj = this.radSvc.Status_Subject;
}
ngAfterViewInit() {
this.subj.subscribe(
(key) => {
const parts = key.split(';');
this.ischecked = (key[0] !== this.instanceId || key[1] !== this.id ? false : true );
}
);
}
ClickEvent($event) {
if (!this.isdisabled) {
this.ischecked = !this.ischecked;
this.radSvc.setRadioChecked(this.instanceId, this.id); // tell the world we got clicked
// send to Store(instanceId, id, value);
}
}
The AfterViewInit() initializes the component's subject (I think) and is supposed to wait for the service to call. When I click on a radiobutton, ClickEvent IS called in the component, I stepped to the setRadioChecked function in the service, the next(key) seems to execute, but it is never caught by the component's AfterViewInit subscribe.
What am I missing?
Thanks for the help :-)
I created a plunkr with your code and I'm able to get everything working fine: plnkr.co/edit/WzZvZNU6S8uPOb85gqZO