9

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.

Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
Anna F
  • 1,583
  • 4
  • 22
  • 42
  • You can bind placeholder like any other attribute, then just provide an empty string where you don't want one. But you can only have a single placeholder, it's not clear where the array of three values fits in. – jonrsharpe Aug 12 '17 at 20:59
  • 2
    What do you mean by a part here? – FAISAL Aug 12 '17 at 21:06
  • @Faisal I mean, I have 3 different parts, but they all have this component – Anna F Aug 12 '17 at 21:24
  • And _what_ are the parts? What is an example of a part? Can you should an output of what you want to be rendered? – Lazar Ljubenović Aug 29 '17 at 23:42

3 Answers3

14

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>
Lazar Ljubenović
  • 18,976
  • 10
  • 56
  • 91
3

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

James D
  • 1,975
  • 2
  • 17
  • 26
1

for anybody looking for something similar(like I was) - you can also call method from placeholder like that:

[placeholder]="someMethod() ? 'placeholder1' : 'placeholder2'"

winters0
  • 66
  • 1
  • 8
  • 1
    You should try and avoid method calls in your templates as the change detection will have to execute the method each time, you should have a boolean and it's state. – Adrian Brand Aug 20 '19 at 21:52