对于 Angular 来说有些陌生。我的应用程序有一个表单,允许用户创建新的数据条目。该项目的部分要求是某些字段使用自动完成功能。我尝试订阅适当控件上的 valueChanges 属性,但控制台日志语句似乎表明这些仅在构造时触发一次。我尝试确定为什么在将文本输入到输入中时自动完成功能没有被动态过滤,但我找不到它。任何帮助表示赞赏。谢谢。
创建预订组件.ts
filteredOriginCities!: Observable<string[]>;
filteredDestinationCities!: Observable<string[]>;
constructor(private fb: FormBuilder, private bookingService: BookingService) {}
ngOnInit(): void {
// Create form
this.createBookingForm = this.fb.group({
bookingId: ['', Validators.required],
shippingMode: ['', Validators.required],
origin: ['', Validators.required],
destination: ['', Validators.required],
pickupDate: ['', Validators.required],
deliveryDate: ['', Validators.required],
tons: ['', [Validators.required, Validators.max(40.0)]]
});
// Subscribe to changes in origin and destination city fields for autocomplete
this.filteredOriginCities = this.createBookingForm.get('origin')!.valueChanges.pipe(
startWith(''),
map(value => {
console.log('Filtering on value: ' + value);
return this._filterCities(value);
})
);
this.filteredDestinationCities = this.createBookingForm.controls['destination'].valueChanges.pipe(
startWith(''),
map(value => this._filterCities(value)),
);
}
创建预订组件.html
<!-- Enter Origin and Destination City Fields -->
<mat-form-field appearance="fill">
<mat-label>Origin City</mat-label>
<input matInput formControlName="origin" [matAutocomplete]="originAuto">
<mat-autocomplete #originAuto="matAutocomplete">
<mat-option *ngFor="let city of filteredOriginCities | async" [value]="city">
{{ city }}
</mat-option>
</mat-autocomplete>
</mat-form-field>
我尝试使用 .controls['origin'] 访问 FormGroup 控件,我尝试为单个控件分配一个单独的变量,然后通过新变量订阅它的 valueChanges 等。我正在使用 Angular 17。
看看 Yong 的演示,这个问题似乎是由于缺少导入 AsyncPipe 或 ReactiveFormsModule 引起的,因为我从未将 [formModule] 指令传递给我的 FormGroup。