I want to transform slug control when user types in the name control. I am applying transformations like changing spaces to hyphens(-), etc.
I created a directive for this which works partially. It does transform the value for slug input field but it doesn't change the value for slug form control when typing on name.
Here is live code: https://stackblitz.com/edit/angular-slug-transform
Directive:
import { Directive, HostListener } from "@angular/core";
import { NgControl } from "@angular/forms";
@Directive({
selector: "[formControlName][appSlugTransform]"
})
export class SlugTransformDirective {
constructor(public ngControl: NgControl) {}
@HostListener("ngModelChange", ["$event"])
onModelChange(event) {
let newVal = this.transform(event);
this.ngControl.valueAccessor.writeValue(newVal);
}
transform(value) {
let text = value.toLowerCase();
if (text.charAt(0) == " ") {
text = text.trim();
}
if (text.charAt(text.length - 1) == "-") {
//text = (text.replace(/-/g, ""));
}
text = text.replace(/ +/g, "-");
text = text.replace(/--/g, "-");
text = text.normalize("NFKD").replace(/[\u0300-\u036f]/g, ""); // Note: Normalize('NFKD') used to normalize special alphabets like óã to oa
text = text.replace(/[^a-zA-Z0-9 -]/g, "");
return text;
}
}
In the example you can see:
- If you type in the
nameinput field, slug gets transformed in its input field but its form control value does not transform. - When you type in the
sluginput field then it works correctly i.e both field and control value get transformed.