Mat*_*att 0 angular2-forms angular-material2 angular angular4-httpclient
我正在将应用程序从 AngularJS 升级到 Angular 5。我想出了大部分事情,但仍然处于学习过程中,我无法找出将自动完成列表连接到后端的最佳方法。Material Design 网站也没有提到这一点。
下面是代码现在的样子:
<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>
Run Code Online (Sandbox Code Playgroud)
我已经删除了 mat-chip-list 并且只包含了相关的代码。
所以我的问题是......现在我从 field.options 获取选项——而不是这个,一旦我开始输入,我如何从 http 后端动态加载它们?
谢谢你的帮助!:)
您可以使用反应式形式来实现这一点。这里的文档:https : //angular.io/guide/reactive-forms。
表单的值变化可以是一个流。您可以根据输入值查询后端。
即(在组件 ts 文件中):
// define appropriate type for your options, string[] just as an example,
// I don't know what you'll receive from the back-end 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 }}
});
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的组件模板中:
<mat-option [value]="opt.id" *ngFor="let opt of autocompleteOptions$ | async">
{{ opt.name }}
</mat-option>
Run Code Online (Sandbox Code Playgroud)
可能需要一些附加功能,例如在此流中过滤以在字符数太少或其他情况下不触发自动完成,但这只是您可以遵循的基本示例。
归档时间: |
|
查看次数: |
4653 次 |
最近记录: |