【问题标题】:How can I assign a value from the Angular Material autocomplete to a variable in my component?如何将 Angular Material 自动完成中的值分配给组件中的变量?
【发布时间】:2017-10-23 20:52:48
【问题描述】:

我正在构建一个表单来创建 API 的 POST。我正在使用 Angular Material 4,并且我正在使用 Material Design 提供的自动完成组件。

这是我的 HTML 组件:

<mat-form-field class="example-full-width">
            <input type="text" matInput placeholder="Local" [formControl]="HomeTeamCtrl" [matAutocomplete]="homeAuto">
            <mat-autocomplete #homeAuto="matAutocomplete">
                    <mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName">
                        {{ team.teamName }}
                    </mat-option>
            </mat-autocomplete>
</mat-form-field>

这很好,我可以输入并过滤结果,然后如果我从列表中选择项目,它会输入到输入字段中并保留在那里。

如您所见,我正在根据对象 Team 的属性过滤列表,该属性来自 Team[] 数组。

这个对象当然还有其他值,我需要做的是当我从我的自动完成选项列表中选择一个值时,它应该调用一个使用同一对象的方法来获取属性中的字符串,解析它并将其分配给一个变量。

这是我的团队课程:

export class Team {
    teamName: string;
    selfLink: string;
}

这是初始数组:

"teams": [{
     "teamName": "River";
     "selfLink": "http://localhost:4200/teams/1"
   },
   {
     "teamName": "Boca";
     "selfLink": "http://localhost:4200/teams/2"
   }]

我创建了初始数组:

ngOnInit(){
    this.match = new Match;
    this.availableTeams = [];
    this.getTeams();
    this.HomeTeamCtrl = new FormControl();
    this.filteredHomeTeams = this.HomeTeamCtrl.valueChanges
        .startWith(null)
        .map(team => team ? this.filterTeams(team) : this.availableTeams.slice());
  }

getTeams() {
    this.teamService.getTeamsList()
      .subscribe(
        teams => this.availableTeams = teams,
        error => console.log(error)
      );
  }

filterTeams(name: string) {
    return this.availableTeams.filter(team =>
      team.teamName.toLowerCase().indexOf(name.toLowerCase()) === 0);
  }

所有这些都有效。现在你可以看到,我有一个“匹配”对象,我需要完成它才能推送它,所以我的问题来了。

如何继续执行以下操作:

当我从自动完成中的选项列表中选择团队名称时,应解析该对象的“selfLink”中的字符串并将 ID 分配给 (最后一个数字) this.match.homeTeam

【问题讨论】:

标签: angular typescript autocomplete angular-material2


【解决方案1】:

最简单的方法是绑定到md-option (onSelectionChange) 并在那里分配局部变量。

<mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName" (onSelectionChange)="match.homeTeam = team.selfLink">

或者在你的组件中调用一个函数

**.html**
<mat-option *ngFor="let team of filteredHomeTeams | async" [value]="team.teamName" (onSelectionChange)="parseHomeTeam(team)">

**.component**
parseHomeTeam(team: Team) {
  // parse team logic here
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-19
    • 2012-05-18
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    相关资源
    最近更新 更多