I'm new to Angular. I'm trying to access/mutate a variable of a parent component from the child component. I've drawn a small diagram to explain my structure.
- Label 1: the parent component where the variable (to be mutated) is situated.
- Label 2: the child component which will change parent's variable on click event.
- Label 3: the button inside child which will trigger the change.
I have checked many solutions like:
- Change parent component state from child component
- Angular access parent variable from child component
- Angular2: child component access parent class variable/function
But I'm not able to solve my problem. I've created an stackblitz also. Please have a look at my code.
timeselector.component.ts
import { Component, ViewChild } from '@angular/core';
import { MonthpickerComponent } from '../monthpicker/monthpicker.component';
@Component({
...
})
export class TimeselectorComponent {
x : boolean=false;
@ViewChild('primaryMonthPicker', {static: false}) primaryMonthPicker: MonthpickerComponent;
recievedFromChild:string="Intentionally left blank";
GetOutputVal($event) {
this.recievedFromChild=$event;
}
}
monthpicker.component.ts
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
...
})
export class MonthpickerComponent {
@Output() outputToParent = new EventEmitter<string>();
constructor() {}
sendToParent(string:string) {
this.outputToParent.emit(string);
}
buttonClicked() {
// some logic to access and change timeselector's x
console.log("Change handler called");
}
ngOnInit() {
}
}
My actual problem is way more complex than this. But I tried to reproduce the same. I just want to see the logic of how it is done, then I'll handle the things my way. I want to change the value of x
to true
.
An expert told me to create a service. But the project is very complex and I can't make changes to it. It's a team project. Is there any quick fix or less painful solution. Please correct me I'm completely blocked because of this. Here is the stackblitz.