2017-10-21 50 views
1

我正在构建一个表单来创建一个POST到API。我正在使用Angular Material 4,并使用Material Design提供的Autocomplete组件。如何将角度材质自动完成中的值分配给我的组件中的变量?

这里是我的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的属性过滤列表。

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

这里是我的团队类:

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

+0

看起来像它在这里:'optionSelections' '可观察'https://material.angular.io/components/autocomplete/ API –

回答

3

最简单的方法是绑定到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 
} 
相关问题