How to update Angular 2 Reactive form field when changes occurred outside of Angular world

六眼飞鱼酱① 提交于 2019-12-12 13:33:36

问题


I recently have started to learn Angular 2 and I am struggling to understand how I should properly connect the changes that occurred in outside world to Angular Reactive Forms.

Specifically, I have an issue with the following example: I want to create a directive that enhances input with autocomplete functionality that provided by typeahead jQuery plugin. My directive looks like the following:

@Directive({
  selector: '[myTypeahead]'
})
class TypeAheadDirective implements AfterViewInit 
{
  constructor(private el: ElementRef) {
  }
  //this will be used as a parameter to source, it is not important for this example
  @Input() myTypeahead: string;
  ngAfterViewInit() {
    let source = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      prefetch: 'http://twitter.github.io/typeahead.js/data/films/post_1960.json'
    });
    $(this.el.nativeElement).typeahead(null, {source, display: 'value'});
  }
}

Then I bind it in an input element in my component like this:

@Component({
  selector: 'my-app',
  template: `
    <form (ngSubmit)="save()" [formGroup]="someForm">
      <h2>Hello {{name}}</h2>
      <input formControlName="name" myTypeahead="'http://someRemoteUrl'"/>
    </form>

    <div class="example">Form model: {{someForm.value | json}}</div>
  `,
})
export class App implements OnInit {
  someForm: FormGroup;
  name:string;
  constructor(private fb: FormBuilder) {
    this.name = `Angular! v${VERSION.full}`
  }

  ngOnInit() {
    this.someForm = this.fb.group({
      name: ''
    });
  }

  save(){

  }
}

Here is a plunker with my example

When I start typing something into input - the binding to my FormGroup works as expected. But when I pick some hint from autocomplete - it updates input, but doesn't propagate the updated value to my form group.

So my question is if it is possible to signal to a form group about the change that has occurred in the directive?

A possible solution could be to make a component that implements ControlValueAccessor to notify about changes, but I want to keep this thing simple with a directive that accepts URL to a data source.


回答1:


Inside Directive :

You can use @Output to send an event and capture it in the form

@Output typeaheadResult = new EventEmitter(); 

...

// Whenever user selects a result dispatch the event 
this.typeaheadResult.emit(changedInput);

Inside your HTML you can capture it

 <input formControlName="name"
          myTypeahead="'http://someRemoteUrl'"
          (typeaheadResult)="doSomething()"
           />


来源:https://stackoverflow.com/questions/44558732/how-to-update-angular-2-reactive-form-field-when-changes-occurred-outside-of-ang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!