How to write *ngIf for input placeholder in Angular2?

Anna F picture Anna F · Aug 12, 2017 · Viewed 12k times · Source

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.

Answer

Lazar Ljubenović picture Lazar Ljubenović · Aug 30, 2017

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>