I have implemented a feature to automatically transform the slug when the user inputs the name in a control field. This transformation includes changing spaces to hyphens (-) among other things.
Although I created a directive for this purpose, it seems to only work partially. While it successfully transforms the value for the slug input field, it doesn't update the value for the slug form control when typing in the name.
Here is the live code showcasing the issue: 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;
}
}
The issue can be observed in the example as follows:
- When typing in the
name
input field, the slug gets transformed in its input field but not in its form control value. - Conversely, when typing in the
slug
input field, both the field and control value are correctly transformed.