我想阻止或继续使用当前基于标志选择的选项:
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
}
}
}
如何达到预期的效果。 此外,如果我使用[ngValue],最初选择选项下拉列表中不会显示任何内容。为什么这样?
答案 0 :(得分:1)
有些事情希望能指出你正确的方向。
[ngValue]
应为[value]
this.condition
永远是真的。你没有把它绑定到任何东西来改变它的价值所以不确定它的目的是什么。
您可以使用(ngModelChange)
而不是(change)
事件拆分绑定。 This answer有一个很好的解释。
答案 1 :(得分:0)
你可以使用这样的东西......
@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}
];