I want to implement "TrimDirective", which removes leading and trailing spaces from input fields, with Angular 2 RC 5 and model / reactive forms.
I managed to change the value of the input field, however I am not getting a new value in component in myForm.valueChanges().
See this plunker: http://plnkr.co/edit/ruzqCh?p=preview
How can I initiate an update to a Group form when a directive changes a 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(() => {
let value: string = this.el.value;
if(value && (value.startsWith(' ') || value.endsWith(' '))) {
console.log('trim!');
this.el.value = value.trim();
}
},0);
}
}
source
share