1
<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

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

I have tried using above code but its not working.

8
  • did the answer help Commented Oct 30, 2017 at 7:07
  • @Sajeetharan your answer works without error in console if #role="ngModel" is removed. And I need #role="ngModel" for validation purpose Commented Oct 30, 2017 at 7:19
  • you can still validate using ngModel Commented Oct 30, 2017 at 7:19
  • yes , thank you @Sajeetharan ) Commented Oct 30, 2017 at 7:23
  • user: User; defaultStr = string ngOnInit(){ this.user.role = this.defaultStr } SCREENSHOT prnt.sc/h3rub4 doesnt appear on select , Html is same as you used on plunker Commented Oct 30, 2017 at 7:55

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

in my above select I have #role="ngModel" , its for validation purpose. If I add that as you havent added in your working demo. It doesnt work
0

Change your code to :

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

Comments

0

For selecting the default value you need to use selected property of angular

 <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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.