Search code examples
javascriptangularangular-directive

Make a simple DOM attribute a one-way binding one from a directive


Clearly my goal is to make an element as <input type="text" placeholder="example" /> look likes <input type="text" [placeholder]="'example'" /> after using an angular directive as

import { Directive, HostBinding } from '@angular/core';

@Directive({
  selector: 'input[placeholder]'
})
export class PlaceholderDirective {
  @HostBinding('placeholder') placeholder:string;
  constructor() {
  }
}

But I don't really now how I could take the firstly set placeholder="A placeholder" in a [placeholder]without having an undefined value.


Solution

  • Okay, I answered myself by asking and writing the question, but here it is for those who'll ask themselves this: I imported ElementRef to access the original placeholder value and set it in the constructor directly!

    import { Directive, HostBinding, ElementRef} from '@angular/core';
    
    @Directive({
      selector: 'input[placeholder]'
    })
    export class PlaceholderDirective{
      @HostBinding('placeholder') placeholder:string;
      constructor(elementRef: ElementRef) {
        this.placeholder = elementRef.nativeElement.placeholder;
      }
    }