Last active
June 17, 2020 23:49
-
-
Save DevEarley/c78d3ffabafa7e56c76c1926a624f968 to your computer and use it in GitHub Desktop.
Using ngModel to Select something with Angular. With disabled options, callback and default value.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<select [ngModel]="vm.selectedThing" | |
(ngModelChange)="onSelectThing($event)"> | |
<option [value]="null">-</option> | |
<option *ngFor="let thing of vm.things" | |
[value]="thing.id" | |
[disabled]="thing.isDisabled"> | |
{{thing.name}} | |
</option> | |
</select> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Standard Angular component. Make sure you import FormsModule into your Module! | |
class AngularSelectComponent { | |
vm: { selectedThing : any, things:any[] } = { | |
selectedThing : null, | |
things:[{ | |
name:"thing-1", | |
id:1, | |
isDisabled:false | |
}, | |
{ | |
name:"thing-2", | |
id:2, | |
isDisabled:false | |
}] | |
}; | |
constructor(){ | |
setTimeout(function(){ | |
this.vm.selectedThing = this.vm.things[1].id; | |
}.bind(this), 2000); | |
} | |
onSelectThing($event) { | |
console.log($event); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Codepen - https://codepen.io/DevEarley/pen/QWyGxPj