2016-10-04 6 views
1

Angular2とForm Controlを使用してオートコンプリート入力フィールドを作成しようとしています。Angular2のフォームコントロール値を編集中にイベントを発生させない方法

まず私は次のように私のフォームコントロールを初期化することを決定した:

term = new FormControl(); 

    constructor(private _autocompleteService: AutocompleteService) { 
    this.term.valueChanges 
     .debounceTime(300) 
     .distinctUntilChanged() 
     .flatMap(search => this._autocompleteService.autocomplete(this.urlSearch, search)) 
     .subscribe(
      autocomplete => this.autocomplete = autocomplete, 
      error => console.log(error) 
     ); 
} 

_autocompleteServiceは、サーバに検索要求を送信AN文字列の配列を返します。

私のhtmlテンプレートはこのように見えます。これは、各要素を選択できる入力の下で提案のリストを表示します。

<input type="text" [formControl]="term"/> 
    <ul> 
     <li *ngFor="let suggestion of autocomplete" (click)="selectChoice(suggestions)"> 
      {{ suggestion }} 
     </li> 
    </ul> 

そして、ここで選択機能さ:

selectChoice(choice: string) { 
    this.autocomplete = [];  // We clean the list of suggestions 
    this.term.setValue(choice); // We write the choice in the term to see it in the input 
    this.selected = resp; 
    } 


ここで問題です。 用語の値を編集すると、イベントが送出され、新しい検索リクエストが送信され、新しい候補リストが表示されます。

このイベントの発生を防止し、入力に表示される値を変更する方法はありますか?

+0

問題のある鉛は最後に貼りません。 – Whitecat

答えて

6

docsによると、次の操作を実行できます。

selectChoice(choice: string) { 
    this.autocomplete = [];  // We clean the list of suggestions 
    this.term.setValue(choice, {emitEvent: false}); // We write the choice in the term to see it in the input 
    this.selected = resp; 
} 

emitEvent: falseが放出されることからvalueChangesイベントを防ぐことができます。

emitEventがtrueの場合、この変更により、FormControlのvalueChangesイベントが送出されます。これは、デフォルトではtrue(updateValueAndValidityまで低下します)です。

+1

他に誰かが '{emitEvent:false}'がfirefoxで無視されるという問題がありますか? – Pylinux

+1

@Pylinux - 私はそれがブラウザに依存するとは思わない。私の鉱山はChromeで無視されます... –

関連する問題