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

I recently started learning Angular 2 and I am struggling to figure out how to properly link the changes that have occurred in the outside world to Angular's reactive forms.

Specifically, I have a problem with the following example: I want to create a directive that enhances typing using the autocomplete functions provided by the java plugin. My directive looks like this:

@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 on 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 in the input - the binding to mine FormGroup

works as expected. But when I select some hint of autocomplete - it updates the input but doesn't pass the updated value to my form group.

So my question is, is it possible to inform the form group about the change that has occurred in the directive?

A possible solution would be to create a component that implements ControlValueAccessor

to notify of changes, but I want this thing to be simple with a directive that takes a data source url.

+3


source to share


1 answer


Internal directive:

You can use @Output

to send the event and record 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 grab it

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

      

+1


source







All Articles