html - 通过 MatAutocomplette Angular 路由
问题描述
我正在尝试实现 Angular Material 的自动完成组件:
它工作正常,它至少显示并且我从我的 json 中看到数据。有没有办法在点击事件时进行路由,即从自动完成中选择某些内容到页面?
我的 HTML 目前看起来像这样:
<div class="example-form">
<div class="container">
<form [formGroup]="schoolForm">
<mat-form-field class="example-form">
<input type="text" matInput placeholder="Gib den Namen deiner Schule ein" formControlName="schoolGroup" required
[matAutocomplete]="autoGroup">
<mat-autocomplete #autoGroup="matAutocomplete">
<mat-optgroup *ngFor="let group of schoolGroupOptions | async" [label]="group.letter">
<mat-option *ngFor="let name of group.names" [value]="name">
{{name}}
</mat-option>
</mat-optgroup>
</mat-autocomplete>
</mat-form-field>
</form>
<form [formGroup]="schoolForm">
<mat-form-field class="example-form1">
<input type="text" matInput placeholder="Gib den Nachnamen deines Lehrers ein">
</mat-form-field>
</form>
</div>
<button mat-raised-button color="primary" routerLink="/teachers">Ergebnisse anzeigen</button>
</div>
TS应该怎么做。看起来像?
谢谢你的帮助
解决方案
查看文档,我们看到MatAutoComplete
在选择选项时会公开一个事件。
@Output() optionSelected
进一步阅读,我们需要[matAutocomplete]
在我们的文本输入中添加一个指令,并将它传递给我们模板中的自动完成的引用。
为此,我创建了一个mat-autocomplete
并给它#navigable
我们传递给[matAutocomplete]
指令的模板文字名称。
这为我们提供了以下 html 模板
<mat-form-field>
<input type="text" matInput [matAutocomplete]="navigable">
<mat-autocomplete #navigable (optionSelected)="chooseOption($event)">
<mat-option *ngFor="let group of groups" [value]="group.route">{{group.name}}</mat-option>
</mat-autocomplete>
</mat-form-field>
请注意,我们可以绑定到(optionSelected)
,mat-autocomplete
因为它是在为附加输入选择值时要调用的 API 中声明的事件。
在我们的 .ts 文件中
@Component()
export class MyExampleComponent {
// group dummy object, hard-coded for demonstration purposes
// I've chosen to store the route directly on the group.
// You should choose whichever strategy suits your needs
groups = [
{
name: "One",
route: 'one'
},
{
name: "Two",
route: 'two'
},
{
name: "Three",
route: 'three'
}
];
// inject router for navigation
constructor(private router: Router) {}
chooseOption(event: MatAutocompleteSelectedEvent) {
// destructure the value and navigate.
const {option: {value}} = event
this.router.navigate([value]);
}
}
就是这样。我们现在将在下拉列表中选择一个选项后立即导航。
推荐阅读
- python - 我编写了一个代码来检查 python shell 是在 32 位还是 64 位上运行。但是代码打印的是 8 而不是 64
- python - anaconda 中的 keras 或 tensorflow 问题
- javascript - 在没有空白的图像之间淡入淡出
- sql - DolphinDB 服务器中两个表的交集
- caching - 完全关联的缓存能否比直接映射缓存具有更高的未命中率?
- sql - 将行名转换为列名,并按日期求和并显示数据
- json - 如何以 Dart 语言返回列表
- javascript - Array.push 仅推送单个值而不是 JS 中的所有值
- javascript - Javascript foreach 函数
- python - 使用 scipy.sparse.block_diag 时避免内存错误