I have an angualr directive created to convert lowerCase to UpperCase (I know there is an angular pipe for this, but I created this directive to understand the concepts. I actually want similar kind of functionality for other directive). But for some reason, this directive is not called initially for pre-defined model value. However, this is triggered when I update the input text box manually.
I wanted an angular directive to run on page load or show/hide section of the component.
In this example, I wanted to pre-populate the "User Name" text box with "TEST" on page load or show/hide section of the component (this show/hide section will show or hide based on the response from the Service call) because I initialized model value with "test" and defined appUpperCase directive on input text box.
How do we tell angular directive to run on page load or show/hide section of the component.
Here is the appUpperCase directive
@Directive({
selector: '[appUpperCase]'
})
export class UpperCaseDirective implements OnInit {
constructor(private control: NgControl) { }
processInput(value: any) {
return value.toUpperCase();
}
@HostListener('ngModelChange', ['$event'])
ngModelChange(value: any) {
console.log(`directive called ${value}`);
this.control.valueAccessor.writeValue(this.processInput(value));
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(value: any) {
this.control.valueAccessor.writeValue(this.processInput(value));
}
ngOnInit(): void {
}
}
Here is my html file:
<form novalidate (ngSubmit)="submitForm()">
<div class="form-group row">
<label for="UserName" class="col-2 col-form-label">User Name:</label>
<div class="col-4">
<input class="form-control" id="UserName" name="userName" required [(ngModel)]="userName" appUpperCase>
Model: {{ userName }}
</div>
</div>
<button class="btn btn-primary" type="submit">
Search
</button>
</form>
and in component file.
userName: any;
constructor() {
this.userName = 'test';
}
I don't really understand why you're using HostListener (first of all, for keydown.backspace listener, you don't receive a value in the listener but the event).
Why not just listen to the valueChanges stream of the control, and update it there?
Also, you should use ReactiveFormsModule so you can get the value.
// directive.ts
import { Directive, OnDestroy, OnInit } from '@angular/core';
import { NgControl } from '@angular/forms';
import { Subject } from 'rxjs';
import { distinctUntilChanged, startWith, takeUntil } from 'rxjs/operators';
@Directive({
selector: '[appUpperCase]',
})
export class UpperCaseDirective implements OnInit, OnDestroy {
private _destroyed$ = new Subject<void>();
constructor(private control: NgControl) {}
processInput(value: any) {
return value.toUpperCase();
}
ngOnDestroy(): void {
this._destroyed$.next();
this._destroyed$.complete();
}
ngOnInit(): void {
this.control.valueChanges
.pipe(
startWith(this.control.value),
distinctUntilChanged((first, second) => {
return this.processInput(first) === this.processInput(second);
}),
takeUntil(this._destroyed$)
)
.subscribe((value) => {
this.control.control.setValue(this.processInput(value));
});
}
}
// component.ts
import { Component, VERSION } from '@angular/core';
import { FormControl } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
userName = new FormControl('test');
constructor() {}
submitForm() {
console.log(this.userName.value);
}
}
<!--component.html-->
<form novalidate (ngSubmit)="submitForm()">
<div class="form-group row">
<label for="UserName" class="col-2 col-form-label">User Name:</label>
<div class="col-4">
<input
[formControl]="userName"
class="form-control"
id="UserName"
name="userName"
required
appUpperCase
/>
Model: {{ userName.value }}
</div>
</div>
<button class="btn btn-primary" type="submit">Search</button>
</form>