Issue
I'm trying to convert every string input to null upon cahnge. So i create a directive to listen on every change and assign null to empty string.
And here is the HTML
<form [formGroup]="form" class="mt-4 p-2" (ngSubmit)="onSubmit()">
<input nbInput fullWidth fieldSize="small" shape="semi-round" formControlName="AuthorityNum" EmptyToNull>
</form>
Here is the directive code:
import { Directive, Input, HostListener, ElementRef } from
'@angular/core';
@Directive({
selector: '[EmptyToNull]'
})
export class NullValueDirective {
constructor() {
}
@HostListener('change', ['$event.target.value']) onKeyDowns(value) {
if (value === '') {
value = null;
console.log(value) // print: null
}
}
}
It looks like it change the value to null
But when i submit the form and inspect the form.value it appears as empty string again.
why?
Update:
Here is my submit function:
onSubmit() {
// TODO: Send to server
this.form.value.AuthorityNum === '' // true
}
Here is the code at stackblitz: https://stackblitz.com/edit/angular-ilcg7y
Solution
There are couple of issues with your code:
The directive needs to emit the value back so that can be bound to the respective form control:
export class NullValueDirectiveDirective { @Output('EmptyToNull') response = new EventEmitter<string>(); @HostListener('keyup', ['$event']) onKeyDowns(event: KeyboardEvent) { this.response.emit(null); } }Next on your template you need to bind to the emitted value:
<input formControlName="AuthorityNum" (EmptyToNull) = "form.controls.AuthorityNum.value = $event">
Answered By - Nicholas K
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.