如何根据角度2中的条件自动选择下拉菜单

时间:2018-02-06 13:19:47

标签: javascript angular angular5

我有一个下拉列表,默认情况下没有选择任何值。在我的主页中,我有条件检查查询参数并根据该条件自动选择下拉列表。我尝试过几种方法,但没有奏效。以下是代码:

home.html的:

<div class="col-md-3">
<select (change) = "onAccountTypeSelection()" required="required" class="form-control" [(ngModel)]="accountType">
  <option value="" selected>Select Account Type</option>
  <option *ngFor="let account of accountTypes" [value]="account.id">{{account.name}}</option>
</select>
</div>

home.js:

private accountTypes = Array<KeyValuePair>();
public ngOnInit() {
this.accountTypes = Array<KeyValuePair>();
this.accountTypes.push(new KeyValuePair('Saving', 'Saving'));
this.accountTypes.push(new KeyValuePair('Checking', 'Checking'));
this.accountType = '';
this.route.queryParams.subscribe((params: Params) => {
    console.log("iN HOME",params['account'],this.accountTypes[1]);
    if( params['account'] ){
        console.log("---Inside account type1",this.accountTypes);
        if(params['account'] == "saving"){
          this.accountTypes = this.accountTypes[0].id;//didnt work
        }
        else if(params['account'] == "checking"){
          this.accountTypes = this.accountTypes[1].id;//didnt work
        }
    }
 }

}

有人可以帮助我根据params ['account']自动选择这里的下降..谢谢

2 个答案:

答案 0 :(得分:0)

  

我在角度Js中使用此方法可能对您有所帮助。只需指出你想要选择的ng-model并使用这个选择菜单它肯定会工作。在你的方法中我也遇到了麻烦,但这对于先生来说是有用的。

<select class="form-control" ng-model="selectedProviderList" ng-options="data.provider_id as data.doctor_name for data in DataArray">

答案 1 :(得分:0)

试试这个: -

<div class="col-md-3">
<select (change) = "onAccountTypeSelection()" required="required" class="form-control" [(ngModel)]="accountType">
<option value="" selected>Select Account Type</option>
<option *ngFor="let account of accountTypes" *ngIf="toBeSelected == account.name" [value]="account.id">{{account.name}}</option>
</select>
</div>

------------------------------------------- 

 private accountTypes = Array<KeyValuePair>();
 private toBeSelected= null;
 public ngOnInit() {
        this.accountTypes = Array<KeyValuePair>();
        this.accountTypes.push(new KeyValuePair('Saving', 'Saving'));
        this.accountTypes.push(new KeyValuePair('Checking', 'Checking'));
        this.accountType = '';
        this.route.queryParams.subscribe((params: Params) => {

        console.log("iN HOME",params['account'],this.accountTypes[1]);

        if( params['account'] ){
        console.log("---Inside account type1",this.accountTypes);
        if(params['account'] == "saving"){
            this.toBeSelected = "saving";
        }
        else if(params['account'] == "checking"){
            this.toBeSelected = "checking";
       }
     }
   }
 }