首页 > 解决方案 > 通过 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应该怎么做。看起来像?

谢谢你的帮助

标签: htmlangulartypescript

解决方案


查看文档,我们看到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]);
  }

}

就是这样。我们现在将在下拉列表中选择一个选项后立即导航。


推荐阅读