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



我有一个模板

<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 部分 - 我不需要任何占位符。

您可以使用 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>

我正在对布尔值使用类似的情况。

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

这是一个堆栈闪电战演示,其中包含您使用此方法提供的信息

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

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

最新更新