0

I am working with reactive forms:

This is my form in html file:

<select class="form-group form-control" formControlName="Control{{prop.id}}" id="Control {{prop.id}}" name="Control{{prop.id}}" [required]="prop.mandatory" (change)="changeDropdown ($ event, prop.id)">
  <option value=""> Select </option>
  <option *ngFor="let data of dataMap.get (prop.id)" value="{{data.value}}">{{data.text}} </option>
</select>

From the ts file I want to select the option I need, when I do this it works perfectly:

this.formLoad.controls ['Control' + id] .setValue (1);

Now I want to select the option with the value = "" (value name: Select):

this.formLoad.controls ['Control' + id] .setValue ("");

This is not working for me, what could be the problem?

Thank you,

2
  • Maybe trying setting the value to "0" or "-1" (if 0 "0" is used). Commented Aug 9, 2020 at 10:35
  • Do you get any errors when trying to set to an empty string? Commented Aug 9, 2020 at 11:26

2 Answers 2

1

You can assign some value to the option select as well. And set that value from the .ts file when you want some option to be selected. And when you want to use that data to set it in some object or something, you can just add one condition of the value should not be equal to that select.

Suppose you keep default as the value.

So update your code as below:

<select class="form-group form-control" formControlName="Control{{prop.id}}" id="Control {{prop.id}}" name="Control{{prop.id}}" [required]="prop.mandatory" (change)="changeDropdown ($ event, prop.id)">
  <option value="default"> Select </option>
  <option *ngFor="let data of dataMap.get (prop.id)" value="{{data.value}}">{{data.text}} </option>
</select>

and

this.formLoad.controls ['Control' + id] .setValue ("default");

When you use this selected option, add this.

if(selectedValue !== 'default'){
.........
}
Sign up to request clarification or add additional context in comments.

Comments

1

There is a lot of code missing here to make everything works so I will make some assumptions. You might want to use reactive forms api:

this.formLoad.get('Control' + id).setValue(1);

Then you can try to set it like this:

this.form.get('Control' + id).setValue('')

This API usually gives you better control.

I tried to reproduce this with a stackblitz:

https://stackblitz.com/edit/angular-ivy-seuwh4?file=src%2Fapp%2Fapp.component.ts

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.