javascript - 如何在 Angular 应用程序中创建多行 mat-autocomplete 元素
问题描述
我正在构建一个角度应用程序。在我有按钮的模板中,单击它会添加新的自动完成元素。但是当我选择一个选项时出现问题,我看到其他自动完成显示先前过滤的值。我过滤方法和表单控件对于所有自动完成元素都是通用的。我试图弄清楚,如何使每个自动完成元素的表单元素和过滤器方法都是唯一的。
任何帮助或建议将不胜感激,谢谢。
这是代码片段,
模板.html
<button (click)="addelement()"> Add New Elemnt </button>
<ng-container *ngFor="let name of names; let j = index">
<form class="example-form">
<mat-form-field class="example-full-width">
<mat-label>Assignee</mat-label>
<input type="text" matInput [formControl]="myControl" [matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option">
{{option.name}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</form>
</ng-container>
模板.ts
import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {Observable} from 'rxjs';
import {map, startWith} from 'rxjs/operators';
export interface User {
name: string;
}
/**
* @title Display value autocomplete
*/
@Component({
selector: 'autocomplete-display-example',
templateUrl: 'autocomplete-display-example.html',
styleUrls: ['autocomplete-display-example.css'],
})
export class AutocompleteDisplayExample implements OnInit {
myControl = new FormControl();
options: User[] = [
{name: 'Mary'},
{name: 'Shelley'},
{name: 'Igor'}
];
names=[{}]
filteredOptions: Observable<User[]>;
ngOnInit() {
this.filteredOptions = this.myControl.valueChanges
.pipe(
startWith(''),
map(value => typeof value === 'string' ? value : value.name),
map(name => name ? this._filter(name) : this.options.slice())
);
}
displayFn(user: User): string {
return user && user.name ? user.name : '';
}
private _filter(name: string): User[] {
const filterValue = name.toLowerCase();
return this.options.filter(option => option.name.toLowerCase().indexOf(filterValue) === 0);
}
addelement() {
this.names.push({});
}
}
在上面的代码片段中,您将“names”数组,根据推送到此数组的对象,自动完成将出现在模板中。如果您需要更多信息,请告诉我。
解决方案
推荐阅读
- c# - Check for exception type inside Exception catch block and log it
- ios - UIScrollView detect when user drags scroll bars
- amazon-web-services - Starting a new execution of Step Function after exceeding 25,000 events, when iterating through objects in an S3 bucket
- javascript - Calling a javascript function inside another function is considered undefined
- flutter - 为什么在 Dart/Flutter 中将 Future 类称为 Future API?
- c# - 如何将 TryParse 与 Console.Readile 一起使用?
- java - 每次我从 spring.io 创建 Spring Boot 项目时都会创建 ServletInitializer 文件
- asynchronous - 如何让 Google 的 SpeechClient.StreamingRecognize.WriteAsync 更快?
- matlab - MATLAB MILP 优化问题与目标函数的求和以及受制于的方程
- r - 我想根据没有 rbind 的序列号连续修改几列,因为列标题不相同