Reputation: 175
I am an enthusiastic newbie trying to understand better Angular2. I would like to make a condition.
What Do I want to do? Disabled the first option of a dropdown.
What is the conditional? If var is equal to XX add disabled
Data
export class SuperComponent {
moon = ['Select One Option', 'Option 1', 'Option 2','Option 3'];
}
Template
<option *ngFor="let OptionsList of moon" *ngIf="OptionsList==='Select One Option'" disabled>
<span>{{OptionsList}}</span>
</option>
so, any suggestion?
Upvotes: 0
Views: 2276
Reputation: 16540
You don't need *ngIf
in this situation, you can use attribute binding. Simply:
<option *ngFor="let OptionsList of moon" [attr.disabled]="OptionsList==='Select One Option'">
<span>{{OptionsList}}</span>
</option>
And, since disabled
is an attribute and a property of option
, even shorter:
<option *ngFor="let OptionsList of moon" [disabled]="OptionsList==='Select One Option'">
<span>{{OptionsList}}</span>
</option>
Upvotes: 4
Reputation: 1421
ngIf will remove whole component <option></option>
if the result is true. To add actually <option disabled></option>
I would suggest next approach.
To use disabled it has to be injected so at first I would make a directive
@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');
}
}
}
Now you can use [sdDisabled] to attach disables property
<option *ngFor="let OptionsList of moon" [sdDisabled]="OptionsList==='Select One Option'">
<span>{{OptionsList}}</span>
</option>
Upvotes: 2