如何在 Angular2 中为输入占位符编写 *ngIf?

How to write *ngIf for input placeholder in Angular2?

我有模板

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

我也有一个数组myWords

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

我怎么能像占位符一样插入这些词,但只有在特殊情况下,比如

this.app-part

我的应用程序中有 3 个部分,但我只想在第 3 部分有一个占位符(myWords 中的文字),如果我有第 1 部分或第 2 部分 - 我不需要任何那里的占位符。

您可以使用 the conditional operator ?: in JavaScript 将属性 placeholder 设置为一个值或一个空字符串。对于大多数常见用例,将占位符设置为空字符串应该与不设置它相同。

要访问正确的占位符值,您需要将 index 分配给本地模板变量 j

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

对于寻找类似东西的任何人(就像我一样)- 你也可以像这样从占位符调用方法:

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

我正在使用带有布尔值的类似案例。

<!-- 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>

在您的具体示例中,我将使用:

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

这是一个 stackblitz demo,其中包含您使用此方法提供的信息