Reputation:
I want to prevent or continue with the option that is currently being selected based on a flag:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<select [(ngModel)]="selectedStudent" (change)="onSelectChange($event)">
<option *ngFor="let student of list" [ngValue]="student">{{student.name}}</option>
</select>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
private list: Object = [
{name: 'Abc', age: '24'},
{name: 'Def', age: '25'},
{name: 'Ghi', age: '25'},
{name: 'Jkl', age: '25'},
{name: 'Mno', age: '25'}
];
private selectedStudent: Object;
private condition: boolean = true;
onSelectChange(event) {
if (this.condition) {
// select the option being selected
} else {
// prevent any change in option
}
}
}
How to achieve the desired effect. Moreover, if I use [ngValue], initially nothing is shown in the select option dropdown. Why so?
Upvotes: 0
Views: 1341
Reputation: 2190
You can use something like this...
@Component({
selector: 'app-root',
template: `
<select [(ngModel)]="selectedStudent" (ngModelChange)="onSelectChange($event)">
<option *ngFor="let student of list" [ngValue]="student" [disabled]='student.flag'>{{student.name}}</option>
</select>
`,
styleUrls: ['./app.component.css']
})
export class AppComponent {
private list: Object = [
{name: 'Abc', age: '24',flag: true},
{name: 'Def', age: '25',flag: false},
{name: 'Ghi', age: '25',flag: false},
{name: 'Jkl', age: '25',flag: true},
{name: 'Mno', age: '25',flag: true}
];
Upvotes: 0
Reputation: 4553
A few things to hopefully point you in the right direction.
[ngValue]
should be [value]
this.condition
is always true. You're not binding it to anything to change it's value so not sure what it's purpose is.
You can split the binding using (ngModelChange)
instead of the (change)
event. This answer has a good explanation.
Upvotes: 1