[英]Understanding a value of *ngIf in Angular2
我是一個熱情的新手,試圖更好地了解Angular2。 我想提出一個條件。
我想做什么? 禁用下拉菜單的第一個選項。
有條件的是什么? 如果var等於XX,則禁用
數據
export class SuperComponent {
moon = ['Select One Option', 'Option 1', 'Option 2','Option 3'];
}
模板
<option *ngFor="let OptionsList of moon" *ngIf="OptionsList==='Select One Option'" disabled>
<span>{{OptionsList}}</span>
</option>
那么,有什么建議嗎?
您不需要*ngIf
在這種情況下,可以使用屬性綁定。 只是:
<option *ngFor="let OptionsList of moon" [attr.disabled]="OptionsList==='Select One Option'">
<span>{{OptionsList}}</span>
</option>
而且,由於disabled
是option
的屬性和屬性,甚至更短:
<option *ngFor="let OptionsList of moon" [disabled]="OptionsList==='Select One Option'">
<span>{{OptionsList}}</span>
</option>
如果結果為true,則ngIf將刪除整個組件<option></option>
。 要實際添加<option disabled></option>
我建議采用下一種方法。
要使用禁用它必須被注入,所以一開始我會做一個指令
@Directive({
selector: '[sdDisabled]',
})
export class sdDisabled {
@Input('sdDisabled') isDisabled: boolean;
constructor(private el: ElementRef) {}
@Input() set sdDisabled(condition: boolean) {
if (condition) {
this.el.nativeElement.setAttribute('disabled');
} else {
this.el.nativeElement.removeAttribute('disabled');
}
}
}
現在您可以使用[sdDisabled]附加disables屬性
<option *ngFor="let OptionsList of moon" [sdDisabled]="OptionsList==='Select One Option'">
<span>{{OptionsList}}</span>
</option>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.