简体   繁体   English

如何从Angular2的组件中更改选择选项?

[英]How do I change the select option from the component in Angular2?

I have a dropdown like below 我有一个如下所示的下拉列表

html html

<mat-form-field>
  <mat-select placeholder="Team" [(ngModel)]="selectedTeam" name="team"
              (change)="mainValuesChanged('team',$event,t.value)" #t>
      <mat-option *ngFor="let team of teams" [value]="team.value"  >
      {{ team.viewValue }}
      </mat-option>
  </mat-select>
</mat-form-field>

ts ts

selectedTeam="team1"
teams = {"value":"t1","viewValue":"team1",
         "value":"t2","viewValue":"team2",
         "value":"newTeam",""viewValue":"Create Team"}

What I'd like to do is when the user clicks on 'Create Team' the previous values(t1:team1 or t2:team2) remain same, while I create a new team by form, etc. 我想做的是,当用户单击“创建团队”时,以前的值(t1:team1或t2:team2)保持不变,而我通过表单创建新团队等。

How do I get reference to the select element so that I can change [value] to the previous value? 如何获得对select元素的引用,以便可以将[value]更改为先前的值?

So far I have this: 到目前为止,我有这个:

mainValuesChanged(term,event:MatSelectChange,tValue){
    if (event.value==="newTeam"){
        this.selectedTeam = getPrevTeamNamefromAService();
        #hack, hack 
    }
}

If I could only reference the select element and set the [value] to selectedTeam or just change the selected value from the component without a direct reference, I would be able to do this. 如果我只能引用select元素并将[value]设置为selectedTeam,或者仅从组件中更改选择的值而无需直接引用,则可以做到这一点。 How do I achieve this? 我该如何实现?

If you take a look at the API docs for the select , you can see that MatSelect is exported as matSelect . 如果看一下selectAPI文档,则可以看到MatSelect导出为matSelect This means that you can get a reference to the select in the template by writing #t="matSelect" . 这意味着您可以通过编写#t="matSelect"来引用模板中的选择。 If you then pass this #t into your function, you can update the select's value like this: 如果随后将此#t传递给函数,则可以像下面这样更新select的值:

mainValuesChanged(term, event:MatSelectChange, select: MatSelect){
    if (event.value==="newTeam"){
        select.writeValue(getPrevTeamNamefromAService());
    }
}

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM