简体   繁体   中英

Change type of input depending on a dropdown in Angular?

I have a dropdown next to an input field and I'm trying to create the input field such that it could dynamically change its type depending on the value selected in the dropdown. So if the user selects 'Text' from the dropdown, the type of the input would be 'text'.

Here is my HTML:

            <div class="input-group"">
              <div class="input-group-prepend">
                <span class="input-group-text" id="addCardio">Name</span>
              </div>
              <select
                class="form-control"
                [ngModel]="cardioInputType"
                [ngModelOptions]="{standalone: true}"
              >
                <option value="text">Text</option>
                <option value="number">Number</option>
              </select>
              <input
                  class="form-control"
                  [type]="cardioInputType"
              />
            </div>

Here is my TS file:

  cardioInputType: string = 'text';

  constructor() {}

  ngOnInit(): void {
    ...
  }

  ...
}

There aren't any errors but it doesn't seem to change when I select a dropdown value.

just use two way data binding [()] for your ngModel

[(ngModel)]="cardioInputType"

Use 2 way binding in ngModel

Change

<select
    class="form-control"
    [ngModel]="cardioInputType"
    [ngModelOptions]="{standalone: true}"
>

To

<select
    class="form-control"
    [(ngModel)]="cardioInputType"
    [ngModelOptions]="{standalone: true}"
>

Demo: https://angular-ivy-brdaba.stackblitz.io/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM