简体   繁体   English

使用 ngModel 和 name 属性时,Angular2 选择默认值不起作用

[英]Angular2 select default value not working when ngModel and name attribute is used

<select id="role" name="role" class="form-control" [(ngModel)]="user.role" #role="ngModel" required>
    <option value="" >Select</option>
    <option value="leadAnalyst">Lead Analyst</option>
    <option value="analyst">Analyst</option>
    <option value="assistant">Assistant</option>
</select>

user-create.component.ts用户创建.component.ts

ngOnInit() {
  this.user.role = 'Select';
}

I have tried using above code but its not working.我试过使用上面的代码,但它不起作用。

You need to define user as a object and then assign the value for the role,您需要将用户定义为对象,然后为角色分配值,

export class AppComponent {
  defaultStr = 'Select';
  user = { role: this.defaultStr };

  constructor() { console.clear(); }
  getvalue(){
    console.log(this.user.role);
  }
}

WORKING DEMO

Change your code to :将您的代码更改为:

ngOnInit() {
        this.user.role = '';
    }

For selecting the default value you need to use selected property of angular要选择默认值,您需要使用 angular 的 selected 属性

 <select id="role" name="role" class="form-control"  #role="ngModel" required>
    <option value="" >Select</option>
    <option value="leadAnalyst" [selected]="'leadAnalyst' == user.role">Lead Analyst</option>
    <option value="analyst" [selected]="'Analyst' == user.role">Analyst</option>
    <option value="assistant" [selected]="'assistant' == user.role">Assistant</option>
</select>

"User.role" should return the role of user in ngOnInit() "User.role" 应该在 ngOnInit() 中返回用户的角色

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

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