gpt4 book ai didi

angular - 创建可重用的 matAutocomplete 指令

转载 作者:行者123 更新时间:2023-12-05 01:44:09 24 4
gpt4 key购买 nike

我想实现一个组件或指令以与 Angular Material 一起使用 autocomplete component .然而,我很难弄清楚如何封装业务逻辑并将其连接起来,同时仍然暴露输入元素,以便轻松设置样式和添加可访问性。

理想情况下,我希望有一个指令可以添加到输入中,但我的理解是您需要实例化 <mat-autocomplete>零件。因此,我尝试创建一个组件来实例化 <mat-option>列表。

@Component({
selector: 'employee-search',
exportAs: 'employeeSearch',
template: `
<mat-option *ngFor="let employee of employees | async" [value]="employee.globalId">
<span>
<span>{{ employee.name }}</span> |
<small>{{ employee.globalId }}</small>
</span>
</mat-option>
`,
})
export class EmployeeComponent implements OnInit {
control = new FormControl();
employees: Observable<any[]>;

constructor(private rest: MyRestService) { }

ngOnInit() {
this.employees = this.control.valueChanges
.filter((value: string) => value && value.length >= 3)
.debounceTime(300)
switchMap((value: string) => this.loadEmployees(value));
}

loadEmployees(searchInput: string): Observable<any[]> {
return this.rest.get('/employees', { filter: searchInput });
}
}

我尝试在 <mat-autocomplete> 中使用这个组件组件,它似乎确实在进行 http 调用以加载数据,但未加载选项。

<mat-form-field>
<input matInput placeholder="Employee" aria-label="Employee"
[matAutocomplete]="auto"
[formControl]="employee.control">
</mat-form-field>
<mat-autocomplete #auto="matAutocomplete">
<employee-search #employee="employeeSearch"></employee-search>
</mat-autocomplete>

如何创建一个组件或指令来使输入显示我的自定义自动完成列表?

最佳答案

我通过包装 <mat-autocomplete> 来实现它并将其传递给输入。

@Component({
selector: 'employee-search',
exportAs: 'employeeSearch',
template: `
<mat-autocomplete>
<mat-option *ngFor="let employee of employees | async" [value]="employee.globalId">
<span>
<span>{{ employee.name }}</span> |
<small>{{ employee.globalId }}</small>
</span>
</mat-option>
</mat-autocomplete>
`,
})
export class EmployeeComponent implements OnInit {
control = new FormControl();
employees: Observable<any[]>;

@ViewChild(MatAutocomplete) autocomplete: MatAutocomplete;

constructor(private rest: MyRestService) { }

ngOnInit() {
this.employees = this.control.valueChanges
.filter((value: string) => value && value.length >= 3)
.debounceTime(300)
switchMap((value: string) => this.loadEmployees(value));
}

loadEmployees(searchInput: string): Observable<any[]> {
return this.rest.get('/employees', { filter: searchInput });
}
}

然后使用模板引用变量,我能够访问控件和自动完成属性。

<mat-form-field>
<input matInput placeholder="Employee" aria-label="Employee"
[matAutocomplete]="employee.autocomplete"
[formControl]="employee.control">
</mat-form-field>
<employee-search #employee="employeeSearch"></employee-search>

关于angular - 创建可重用的 matAutocomplete 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47060906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com