I am trying to build an angular app containing two sibling components - Welcome & Questions. The Welcome template has a textbox for username and I want to display that username in my Question component template. For this, I have written a service to communicate between these two sibling components. Here are my codes -
username.service.ts
export class UsernameService {
name = new EventEmitter<string>();
}
welcome.component.ts
export class WelcomeComponent {
username: string = '';
@ViewChild('username') usernameInput: ElementRef;
constructor(private unameService: UsernameService){}
onStartQuiz(){
this.username = this.usernameInput.nativeElement.value;//the value is correct
this.unameService.name.emit(this.username);
}
}
question.component.ts
export class QuestionComponent implements OnInit {
username: string = '';
constructor(private unameService: UsernameService) { }
ngOnInit(): void {
this.unameService.name.subscribe((data) => {
console.log(data); //This is not getting printed
});
}
}
Inside subscribe, nothing is getting printed. I also tried using Subjects but then also the result is same. I have also provided the service in app.module .I am not able to understand what the problem is.