我正在尝试使用两个matInput字段,每个字段都与单独的mat-autocomplete面板绑定。按照here的步骤操作,我可以正常工作,但是在使用两个输入字段和自动完成面板方面遇到困难。
这是我的html:
<form>
<mat-form-field>
<input matInput [matAutocomplete]="first" [formControl]="myControl">
<mat-autocomplete #first="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions1 | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field>
<input matInput [matAutocomplete]="second" [formControl]="otherControl">
<mat-autocomplete #second="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions2 | async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
这是我的组成部分:
import { Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
@Component({
selector: 'app-property-create',
templateUrl: './property-create.component.html',
styleUrls: ['./property-create.component.css']
})
export class PropertyCreateComponent implements OnInit {
myControl = new FormControl();
otherControl = new FormControl();
options1: string[] = ['One', 'Two', 'Three'];
options2: string[] = ['Four', 'Five', 'Six'];
filteredOptions1: Observable<string[]>;
filteredOptions2: Observable<string[]>;
constructor() { }
ngOnInit() {
this.filteredOptions1 = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter(value))
);
this.filteredOptions2 = this.otherControl.valueChanges
.pipe(
startWith(''),
map(value => this._filter2(value))
);
}
private _filter(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options1.filter(option => option.toLowerCase().includes(filterValue));
}
private _filter2(value: string): string[] {
const filterValue = value.toLowerCase();
return this.options2.filter(option => option.toLowerCase().includes(filterValue));
}
}
将每个文本输入字段链接到相应的面板时,我正在使用[matAutocomplete] =“ first”将第一个面板链接到第一个文本输入。基于Angular Material文档,我期望能够通过使用[matAutocomplete] =“ second”将第二个文本输入字段链接到第二个自动完成面板。
现在,我的自动填充面板显示在同一位置,而不是在相应的文本字段下方。
有人看到过这个吗,或者知道我在做什么错吗?
答案 0 :(得分:0)
结果是您缺少form和mat-form-field元素的css类:
<form class="example-form">
<mat-form-field class="example-full-width">
<input placeholder="Pick one" aria-label="Number" matInput [formControl]="myControl" [matAutocomplete]="first">
<mat-autocomplete #first="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions1|async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
<mat-form-field class="example-full-width">
<input placeholder="Pick one" aria-label="Number" matInput [formControl]="otherControl" [matAutocomplete]="second">
<mat-autocomplete #second="matAutocomplete">
<mat-option *ngFor="let option of filteredOptions2| async" [value]="option">
{{option}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>