How to set the default value inside a HTML Text box element using Angular Directive . Please refer the below code

2020-02-14 javascript html angular angular-directive dom-manipulation

Below code works fine for changing innerHTML of "div , heading tags" but not working for textboxes

@Component({
  selector: 'app-root',
  template: ` <h3 appNamevalidation >Angular 7 Template-Driven Form Validation</h3>
  <input type = "text" [(ngModel)]="model.firstName" #firstName="ngModel" required appNamevalidation 
  />`
})

@Directive({
  selector: '[appNamevalidation]'
})

export class NamevalidationDirective {
  constructor(private elem: ElementRef) { }

  ngOnInit() {
    console.log(' inside ngOninIt directive hook');
    this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
    this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
  }
}

Answers

The ngOnInit hook of your directive gets executed before the binding of your ngModel on your input. You could use another Lifecycle hook like ngAfterViewChecked to make it work:

export class NamevalidationDirective {
    constructor(private elem: ElementRef) { }

    ngAfterViewChecked() {
        this.elem.nativeElement.value = "Changed by directive inside NG ONIT";
        this.elem.nativeElement.innerHTML = "Changed by directive inside NG ONIT";
    } 
} 

Related