Home > Software engineering >  Unable to display a reusable select input(dropdown) component in Angular form
Unable to display a reusable select input(dropdown) component in Angular form

Time:09-26

I am trying to implement select-input(dropdown) component in Angular register form. Here is the implementation of my reusable select-input component:

select-input.component.ts

@Component({
  selector: 'select-input',
  templateUrl: './select-input.component.html',
  styleUrls: ['./select-input.component.css']
})
export class SelectInputComponent implements ControlValueAccessor 
{
  @Input() label: string;
  @Input() name: string;
  @Input() options: {value: number; description: string}[];
  
  constructor() { }

  writeValue(obj: any): void
  {
    
  }
  registerOnChange(fn: any): void
  {
    
  }
  registerOnTouched(fn: any): void
  {
    
  }
}  

select-input.component.html

<div>
    <label for={{name}} style="margin-right: 2px;">{{label}}:</label>
    <select name={{name}}>
        <options *ngFor="let option of options" [value]="option.value">
            {{option.description}}
        </options>
    </select>
</div>

register.component.ts

export class RegisterComponent implements OnInit 
{
  countries: {value: number, description: string}[] = [
    {value: 0, description: 'Canada'},
    {value: 1, description: 'USA'},
    {value: 2, description: 'England'},
    {value: 3, description: 'Japan'},
  ]
  registerForm: FormGroup;

  constructor (private fb: FormBuilder) {}

  ngOnInit(): void 
  {
    this.initializeForm();
  }
  
  initializeForm()
  {
    this.registerForm = this.fb.group({
      username: ['', Validators.required],
      country: [this.countries]
    })
    
  }
}

register.component.html

<select-input [formControl]='registerForm.controls["country"]' ngDefaultControl
        [label]='"Country"' [name]='"countries"' [options]="countries">
</select-input>

When i run the application i see the empty dropdown element but when i check the html i see the values in options element like the image below enter image description here

CodePudding user response:

Mistake is in select-input.component.html - <options> need to changes to <option>

<div>
    <label for={{name}} style="margin-right: 2px;">{{label}}:</label>
    <select name={{name}}>
        <option *ngFor="let option of options" [value]="option.value">
        {{option.description}}
        </option>
    </select>
</div>

ref: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select

  • Related