av0*_*000 6 autocomplete typescript angular-material2 angular
有没有办法让自动填充工作在表单中?我有一个输入地址的表单.我正在使用自动完成(从Material Design的文档中复制)用于状态(这在美国),并且除了所选状态未设置为user.state之外,它正在工作.因此,当我在控制台上注销提交时的myForm.form.value时,它看起来像这样:
user.name : "Test"
user.phone: ...
etc.
Run Code Online (Sandbox Code Playgroud)
用户.state甚至没有出现.
我的(相关)代码:
<md-input-container>
<input
mdInput
placeholder="State"
[mdAutocomplete]="auto"
[formControl]="stateCtrl"
name="user.state"
[(ngModel)]="user.state"
>
</md-input-container>
<md-autocomplete
#auto="mdAutocomplete"
>
<md-option
*ngFor="let state of filteredStates | async" [value]="state"
(onSelectionChange)="selectState(state)"
>
{{ state }}
</md-option>
</md-autocomplete>
Run Code Online (Sandbox Code Playgroud)
TS:
constructor(public dialog: MdDialog,) {
this.stateCtrl = new FormControl();
this.filteredStates = this.stateCtrl.valueChanges
.startWith(null)
.map(name => this.filterStates(name));
}
filterStates(val: string) {
return val ? this.states.filter(s => new RegExp(`^${val}`, 'gi').test(s))
: this.states;
}
Run Code Online (Sandbox Code Playgroud)
即使我尝试使用(onSelectionChange)调用函数selectState(state)来设置user.state,它仍然不会出现在我console.log表单上提交时.
selectState(value){
this.user.state = value;
}
Run Code Online (Sandbox Code Playgroud)
AJT*_*T82 13
看看这个GitHub示例:使用md-autocomplete进行演示(表单)
有一个反应和模板驱动形式的例子.使用模板驱动表单formControl
完全删除,只需使用[(ngModel)]
而(ngModelChange)
不是.以下是模板驱动解决方案的示例:
<form #f="ngForm">
<md-input-container>
<input mdInput placeholder="State" [mdAutocomplete]="tdAuto" name="state"
#state="ngModel" [(ngModel)]="currentState"
(ngModelChange)="tdStates = filterStates(currentState)">
</md-input-container>
<md-autocomplete #tdAuto="mdAutocomplete">
<md-option *ngFor="let state of tdStates" [value]="state">
<span>{{ state }}</span>
</md-option>
</md-autocomplete>
</form>
Run Code Online (Sandbox Code Playgroud)
在组件中,我们将过滤后的值分配给另一个变量(tdStates
)并保留states
数组中的所有状态:
filterStates(val: string) {
if (val) {
const filterValue = val.toLowerCase();
return this.states.filter(state => state.toLowerCase().startsWith(filterValue));
}
return this.states;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10139 次 |
最近记录: |