簡體   English   中英

如何將Angular Material自動完成中的值分配給組件中的變量?

[英]How can I assign a value from the Angular Material autocomplete to a variable in my component?

我正在構建一個表單來為API創建一個POST。 我正在使用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 []的數組。

這個對象當然還有其他值,我需要做的是當我從我的自動完成選項列表中選擇一個值時,它應該使用同一個對象調用一個方法來獲取屬性中的字符串,解析它並分配它變量。

這是我的團隊課程:

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

最簡單的方法是綁定到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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM