Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write *ngIf for input placeholder in Angular2?

I have a template

<ng-container *ngFor="let text of texts[i]; let j = index">{{text}}
  <input type="text">
      </ng-container>

I also have an array myWords

myWords = ['orange', 'blue', 'green'];

How could I insert these words like a placeholder, but only in special case, like

this.app-part

I have 3 parts in my app, but I would like to have a placeholder (words from myWords) only in 3rd part, and if I have 1st or 2nd part - I don't need any placeholder there.

like image 785
Anna F Avatar asked Aug 12 '17 20:08

Anna F


2 Answers

You can use the conditional operator ?: in JavaScript to set the attribute placeholder either to a value or to an empty string. Setting the placeholder to an empty string should be the same as having it not set for most common use-cases.

To access the correct placeholder value, you'll need to assign index to a local template variable j.

<ng-container *ngFor="let text of texts[i]; let j = index">
  {{ text }}
  <input type=text [placeholder]="condition ? myWords[j] : ''">
</ng-container>
like image 150
Lazar Ljubenović Avatar answered Nov 14 '22 21:11

Lazar Ljubenović


I'm using a similar case with a boolean.

<!-- if extraKilometers is true then I'll type 'Who?' else I'll type 'What?' -->
<textarea class="form-control input-wide-400" 
                              placeholder="{{extraKilometers ? 'Who?' : 'What?'}}" 
                              aria-label="distance" 
                              formControlName="description"
                              rows=2
                              id="transportDescription"></textarea>

In your specific example I'd use:

<ng-container *ngFor="let text of texts; let j = index">{{text}}
  <input type="text" placeholder="{{ myWords[j] }}" >
</ng-container>

Here's a stackblitz demo with the info you've given using this method

like image 29
James D Avatar answered Nov 14 '22 23:11

James D