I want to implement a "TrimDirective", which deletes leading and trailing spaces from input fields, with Angular 2 RC 5 and model driven / reactive forms.
I managed to change the value of the input field, however I don't get a new value in the component in myForm.valueChanges().
See this plunker: http://plnkr.co/edit/ruzqCh?p=preview
How can I trigger a update of the formGroup when the directive changes the value?
template:
<form [formGroup]="myForm">
<input formControlName="name" trim>
</form>
latest value: -{{ latestValue }}-
component:
@Component({
selector: 'my-app',
templateUrl: 'app/app.html'
})
export class AppComponent implements OnInit {
private myForm: FormGroup;
private latestValue: string;
ngOnInit() {
this.myForm = new FormGroup({
name: new FormControl(),
});
this.myForm.valueChanges.subscribe(v => this.latestValue = v.name)
}
}
directive:
@Directive({
selector: '[trim]'
})
export class TrimDirective {
private el: any;
constructor(
el: ElementRef
){
this.el = el.nativeElement;
}
@HostListener('keypress')
onEvent() {
setTimeout(() => { // get new input value in next event loop!
let value: string = this.el.value;
if(value && (value.startsWith(' ') || value.endsWith(' '))) {
console.log('trim!');
this.el.value = value.trim();
}
},0);
}
}
onEventtoonKeyDownthis.el.value = value.trim();updates the input's value and the DOM, but angular's "model" doesn't change. how can the directive force adetectChanges()or emit an event or something/anything (access the component/FormGroup/FormControl ?)