2
votes

I am using Angular material to create select Dropdown of Religion. But the options I provided might not cover all the religion of the world. But I want to give option for the user to enter his/her religion in the field if not found. So, What I want to do, give an option named 'other option' and when he clicks on the option, an input field will be given to the option which will be treated as the 'formcontrolName' value for the the field.

If you provide the code at Stackblitz, it would be great to see clearly.

3
Try this at your end first cause its not a complex one. Facing problem then come back here!Prashant Pimpale

3 Answers

3
votes

This question has been answered before. Here's an answer using an autocomplete: Angular Material Autocomplete - How to allow user to add item not in suggested list?. StackBlitz here.

If you want to use a standard select instead of autocomplete, it would be easier since you would only have to place a "other" option in your list and have special handling for that perhaps via a dialog. Some of the techniques in the autocomplete example might be useful with a select as well.

1
votes

It's simple,

  1. Use a mat-autocomplete
  2. Add an event (blur) to the input, check if the value is not an empty string and if it's not in the options, add to the options
1
votes

You can use text input after or before mat-option and you may need to fix its css. Below code will insert text box in last of all mat-options.

Please don't forget to declare custom_religion as FormControl

<mat-form-field fxFlex>
          <mat-select name="allowedValuesCriteria"
            [(ngModel)]="selectedReligion">
            <mat-option [value]="1">
              Religion 1
            </mat-option>
            <mat-option [value]="2">
              Religion 2
            </mat-option>
            <mat-form-field fxFlex>
              <input matInput [formControl]="custom_religion" name="custom_religion" 
                (keydown)="$event.stopPropagation()">
            </mat-form-field>
            <small></small>
          </mat-select>
        </mat-form-field>