简体   繁体   中英

Angular - input value and select placeholder not working


I'm creating a form that has some select and some input types, as shown below.

    <div id="datiRichiesta">
            <div *ngFor="let d of formDatiRichiesta" class="form-row">

              <input *ngIf="d.type=='text'"
                     type="text"
                     class="form-control"
                     placeholder="{{d.placeholder}}"
                     [(ngModel)]="model[d.name]"
                     name="{{d.name}}"
                     (focus)="$event.target.placeholder = ''"
                     (blur)="$event.target.placeholder = d.placeholder"
                     value="richiesta.prova"/>

              <select *ngIf="d.type=='select'" 
                      class="form-control" 
                      name="{{d.name}}" 
                      [(ngModel)]="model[d.name]"
                      required>
                <option selected disabled value="">{{d.placeholder}}</option>
                <option *ngFor="let b of elencoBanche" value="{{b.id}}">{{b.nome}}</option>
              </select>

            </div>
      </div>

I've got two main issues:

  1. I need to set a value on the input type, but it is not working. I know that I should use something like ngValue , or at least so I've read online, but most examples are referred to angularjs and I got a bit confused. If I simply put [ngValue]="richiesta.prova" the browser complains that Can't bind to 'ngValue' since it isn't a known property of 'input' .
  2. I need to show a placeholder for the select, but it's not working since the first <option> is part of the dropdown list as all the others. On this I don't have a clue, because it should really work as it is.

Any help will be appreciated, maybe with some explanation, I sense I'm missing something about angular binding.
Thanks.

1) NgModel sets the value. If model[d.name] is not empty - it will be set.
https://angular.io/guide/forms
2) How to show placeholder (empty option) in select control in Angular 2?
These 2 lines are redundant:
(focus)="$event.target.placeholder = ''"
(blur)="$event.target.placeholder = d.placeholder"

If your placeholder is not working then it simply means that you have assigned them some value to that input. In your case, I am 100% sure that {{ d.placeholder }} holds some value ( might be value equal to ' '). Assign this value to NULL. Then see the result.

placeholder="{{d.placeholder}}"

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