在我的angular 5应用程序中,我有一些自动完成功能,我只想在输入值发生变化时填充建议。 当有人在输入中正确地调用我的服务以检索前20个匹配结果时,但是在第一个值更改之前也必须调用此服务。所以如果我关注该字段,我可以看到建议而不是没有。
那么如何在价值变化之前第一次拨打我的电话?
这是我的方法:
matchingCustomers = new BehaviorSubject<Customer[]>([]);
ngOnInit() {
this.firstFormGroup.controls['customer'].valueChanges.subscribe(val => {
this.ticketService.getCustomers(val).subscribe(customers => {
this.matchingCustomers.next(customers);
});
});
}
这是自动完成:
<mat-form-field>
<input matInput appEnforcedInputs [formControl]="firstFormGroup.get('customer')" formControlName="customer" #customer placeholder="{{ 'ticketbundle.detail.labels.customer' | translate }}"
[matAutocomplete]="customerAuto" name="customer">
<mat-icon matSuffix>account_circle</mat-icon>
</mat-form-field>
<mat-autocomplete #customerAuto="matAutocomplete" [displayWith]="displayFn">
<mat-option class="mat-option-customers big-height" *ngFor="let customer of matchingCustomers | async" [value]="customer">
<div class="row">
<span>
<i class="material-icons">account_circle</i>
</span>
<span>
<h3>{{customer.name}}</h3>
<p>
<span class="foreground-color">{{customer.city}}
</span> - {{customer.address}}
</p>
<p>
<img src="assets/img/flags16/{{customer.countryAlpha2Code | lowercase}}.png" />{{customer.countryName}}
</p>
<p>
<span class="darkblue">{{customer.username}}</span> -
<i class="material-icons custom-icons">account_balance</i>{{'customer.detail.labels.balance' | translate}} :
<span *ngIf="customer.balance != null" [style.color]="customer.balance < 0 ? 'red' : 'green'">
{{customer.balance | currency:'EUR':'symbol'}} </span>
<span *ngIf="customer.balance == null"> -- </span>
</p>
</span>
</div>
</mat-option>
</mat-autocomplete>
答案 0 :(得分:1)
您可以使用startWith
方法。请注意,即使用户专注于输入,也会获取数据。
this.firstFormGroup.controls['customer'].valueChanges.startWith('').subscribe(val => {
this.ticketService.getCustomers(val).subscribe(customers => {
this.matchingCustomers.next(customers);
});
});