0

저는 AngularJS에서 Angular 5로 앱을 업그레이드하고 있습니다. 대부분의 것들을 알았지 만 여전히 학습 과정에 조금 있습니다. 자동 완성 목록을 백엔드에 연결하는 가장 좋은 방법을 알아낼 수 없습니다. 머티리얼 디자인 웹 사이트는이 중 하나를 언급하지 않습니다.Angular 5 소재, 백엔드 서버에서 mat-options (autocomplete/select 목록에 있음)를 가져옵니다.

다음은 코드가 지금의 모습입니다 :

<mat-form-field> 

    // chips are up here 

    <mat-autocomplete (optionSelected)="chipAdd($event,field)" #auto="matAutocomplete"> 
     <mat-option [value]="opt.id" *ngFor="let opt of field.options"> 
     {{ opt.name }} 
     </mat-option> 
    </mat-autocomplete> 

    </mat-form-field> 

나는 매트 칩 목록을 제거하고 만 관련 코드를 포함 시켰습니다.

내 질문은 ... 지금은 field.options에서 옵션을 얻고 있습니다.이 대신에 입력을 시작하면 http 백엔드에서 어떻게 동적으로로드 할 수 있습니까?

도움 주셔서 감사합니다. :)

답변

1

반응 형을 사용하여이를 달성 할 수 있습니다. 여기에있는 문서 : https://angular.io/guide/reactive-forms.

양식의 값 변경은 스트림이 될 수 있습니다. 입력 값을 기반으로 백엔드를 쿼리 할 수 ​​있습니다.

e.e. (구성 요소 TS 파일) :

// define appriopriate type for your options, string[] just as an example, 
// I don't know what you'll receive from the backend and use as the option: 
public autocompleteOptions$: Observable<string[]>; 

constructor( private http: HttpClient,) { } 

ngOnInit() { 
    // If you don't know how to have reactive form and subscribe to value changes, 
    // please consult: https://angular.io/guide/reactive-forms#observe-control-changes 

    this.autocompleteOptions$ = this.inputFormControl.valueChanges 
    // this inputFormControl stands for the autocomplete trigger input 
    .debounceTime(150) 
    // well, you probably want some debounce 
    .switchMap((searchPhrase: string) => { 
    // "replace" input stream into http stream (switchMap) that you'll subscribe in the template with "async" pipe, 
    // it will run http request on input value changes 
     return this.http.get('/api/yourAutocompleteEndpoint', { search: { 
      value: searchPhrase }} 
     }); 
    } 
} 

그런 다음, HTML에서 :

<mat-option [value]="opt.id" *ngFor="let opt of autocompleteOptions$ | async"> 
    {{ opt.name }} 
</mat-option> 

자동 완성을 트리거하지 스트림에서 필터링과 같은 필요한 몇 가지 추가 기능이있을 수 있습니다 때 문자의 수 너무 낮거나 무언가이지만, 이것은 잠재적으로 따라 할 수있는 기본 예제 일뿐입니다.

+0

절대적으로 답하십시오! 완벽하게 작동합니다. 고마워요 Radoslaw :) – Matt