I am trying to pass an input value from a select input that has a (change) event associated with it from child component to parent element. Would like the variable to get updated every time the variable from the child component is updated.
My question is different from Question, due to my variable changes on a change event and needs to be updated every time the variable changes.
I was able to figure this out using ViewChild and AfterViewInit but I get an error in the console saying: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: 'Testing'.
Figured there has to be an easy way of doing this. Keep in mind I am still new with Angular.
Child Component template:
<form>
<div class="form-group">
<label for="Master-Products">Select Master Product</label>
<select [(ngModel)]="selectedValue" name="pow" (change)="pow = $event.target.value; onKeyUp()" class="form-control" id="Master-Products">
<option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>
</div>
</form>
Child-component:
export class MasterInputComponent {
powers: any[] = [ 'power1', 'power2', 'power3' ];
submitted = false;
pow:string = 'Testing';
selectedValue = null;
constructor() { }
onKeyUp(value): void{
console.log('Value: ',this.pow);
}
Parent-Component-Template:
<div role="tabpanel" class="tab-pane" id="accessories">
<h1>ACCESSORIES</h1>
<h4>Testing: {{power}}</h4>
<master-input (change)="recieveMessage($event.target.value)"></master-input>
<accessories></accessories>
Parent-Component:
export class AppComponent implements AfterViewInit{
@ViewChild(MasterInputComponent) child;
title = 'Having FUN with Angular';
posts: any[];
power:string;
constructor(private service:ProductsService){}
ngAfterViewInit(){
this.power = this.child.pow;
}
recieveMessage(value){
console.log('Event: ',value);
this.power = value;
console.log('Favorite has changed')
}
Any help would be greatly appreciated, thank you!