Angular 2 Material – 在表单中使用MD的自动完成示例
发布时间:2020-12-17 06:56:07 所属栏目:安全 来源:网络整理
导读:有没有办法让自动填充工作在表单中?我有一个输入地址的表单.我正在使用自动完成( copied from Material Design’s docs)用于状态(这是在美国),并且除了所选状态未设置为user.state之外,它正在工作.因此,当我在控制台上注销提交时的myForm.form.value时,它看
有没有办法让自动填充工作在表单中?我有一个输入地址的表单.我正在使用自动完成(
copied from Material Design’s docs)用于状态(这是在美国),并且除了所选状态未设置为user.state之外,它正在工作.因此,当我在控制台上注销提交时的myForm.form.value时,它看起来像这样:
user.name : "Test" user.phone: ... etc. 用户.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> 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; } 即使我尝试使用(onSelectionChange)调用函数selectState(state)来设置user.state,它仍然不会出现在我console.log表单上提交时. selectState(value){ this.user.state = value; } 解决方法
看看这个GitHub示例:
Demo with md-autocomplete (forms)
有一个反应和模板驱动形式的例子.使用模板驱动表单,您可以完全删除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> 在组件中,我们将过滤后的值分配给不同的变量(tdStates)并保留states数组中的所有状态: filterStates(val: string) { if (val) { const filterValue = val.toLowerCase(); return this.states.filter(state => state.toLowerCase().startsWith(filterValue)); } return this.states; } DEMO (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |