How to change input values ​​in directives using model-driven / reactive forms

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(() => { // 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);
    }
}
+4
source share
1 answer

, angular .

let event: Event = document.createEvent("Event");
event.initEvent('input', true, true);
Object.defineProperty(event, 'target', {value: this.elementRef.nativeElement, enumerable: true});
this.renderer.invokeElementMethod(this.elementRef.nativeElement, 'dispatchEvent', [event]);
+3

Source: https://habr.com/ru/post/1652202/


All Articles