skip to Main Content

I have an angular component that calls for some data asynchronously and stores the value on a signal like this.

tipoSignal: WritableSignal<Tipo> = signal({}) as WritableSignal<Tipo>;


ngOnInit(): void {
   this.tipoService.getTipo().subscribe(tipoReturned =>
      this.tipoSignal.set(tipoReturned)
   );
}

On the HTML side I have a dropdown that allows for selection of other tipo options, like this:

<select class="dropdown" title="tipo_dropdown">
   <option *ngFor="let tipo of tiposArray()" [value]="tipo.id_tipo">{{tipo.formfactor}}</option> 
</select>

tiposArray() also gets populated on ngOnInit*

The problem is I have no idea how to make the value stored on tipoSignal() be selected by default on the dropdown.

I tried adding another option tag and using selected but it doesn’t work and even if it did it would create a duplicate entry (since that value is also on tiposArray()). Not sure if it’s worth mentioning but a Tipo object only has a unique id and a formfactor, nothing else.

Any suggestions that wouldn’t make me have to get rid of signals? (the entire app uses signals everywhere, and this component in particular is plaged with them).

2

Answers


  1. Chosen as BEST ANSWER

    Okay, I figured it out. As @vasilv said, my select tag wasn't bound to anything, so bound it using ngModel and turns out it somehow works with signals too (I don't know why I was convinced it wouldn't work, I feel like I've tried that before with no luck).

    The code now looks like this:

    <select class="dropdown" title="tipo_dropdown" [(ngModel)]="tipoSignal().id_tipo">
       <option *ngFor="let tipo of tiposArray()" [value]="tipo.id_tipo">{{tipo.formfactor}}</option> 
    </select>
    

  2. In your example code the select is not bound to any model.
    To only show the default selected value – the one that will come from tipoSignal you can bind it to the select’s value

    <select class="dropdown" title="tipo_dropdown" [value]="tipoSignal()?.id_tipo">
       <option *ngFor="let tipo of tiposArray()" [value]="tipo.id_tipo">{{tipo.formfactor}}</option> 
    </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search