title: angular: directive transform value of form control
body: <p>I want to transform slug control when user types in the name control.
  I am applying transformations like changing spaces to hyphens(-), etc.</p>
  
  <p>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.</p>
  
  <p>Here is live code:
  <a href="https://stackblitz.com/edit/angular-slug-transform" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-slug-transform</a></p>
  
  <p>Directive:</p>
  
  <pre><code>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;
    }
  }
  </code></pre>
  
  <p>In the example you can see:</p>
  
  <ul>
  <li>If you type in the <code>name</code> input field, slug gets transformed in its input field but its form control value does not transform.</li>
  <li>When you type in the <code>slug</code> input field then it works correctly i.e both field and control value get transformed.</li>
  </ul>