How to change incoming @Input value and emit @Output

775 Views Asked by At

I know that this question is very similar with Angular Component Interaction, but my problem is a bit different.

I have also looked ExpressionChangedAfterItHasBeenCheckedError errors but I couldn't fix my issue.

My need is ability to change the incoming input value and emiting it to parent component. When the input value is empty string, I want to change it to null

Here is my code:

value: string;

@Input('ngModel') 
set ngModel(value: string) {

    if(value == '')
    {
      this.value = null;
      this.ngModelChange.emit(null);
    }
    else
    {
      this.value = value;
    }
}
get ngModel(): string {
    return this.value;
}

@Output('ngModelChange')
ngModelChange: EventEmitter<string> = new EventEmitter<string>()

This throws the following error:

AddClassMajorComponent.html:24 ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'model: '. Current value: 'model: null'.

I have used ChangeDetectorRef but I couldn't get succeeded.

How can I fix it?

Thank you.

1

There are 1 best solutions below

1
On

try like this the @Input and @Output syntaxes

@Input() value: string;
@Output() messageToEmit = new EventEmitter<string>();
ngOnInit(){
    if(value == '') {
      this.value = null;
      this.messageToEmit.emit(null);
    }
    else {
      this.value = value;
    }
}