Skip to content

Instantly share code, notes, and snippets.

@Kalpesh300
Created December 12, 2019 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Kalpesh300/a0cd4ab9c1a342ca6764e9fbc5ec3f33 to your computer and use it in GitHub Desktop.
Save Kalpesh300/a0cd4ab9c1a342ca6764e9fbc5ec3f33 to your computer and use it in GitHub Desktop.
Custom Dropdown Control
<app-custom-dropdown [formControl]="dropdownControl"></app-custom-dropdown>
import { Component } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'dropdown-demo';
dropdownControl = new FormControl(null, Validators.required);
}
<div class="btn-group" dropdown>
<button id="button-basic" dropdownToggle type="button"
class="btn btn-primary dropdown-toggle"
aria-controls="dropdown-basic">
{{ selectedOption }} <span class="caret"></span>
</button>
<ul id="dropdown-basic" *dropdownMenu class="dropdown-menu"
role="menu" aria-labelledby="button-basic">
<li role="menuitem" *ngFor="let option of options" (click)="changeSelectedOption(option)">
<span class="dropdown-item"> {{ option }} </span>
</li>
</ul>
</div>
import { Component, OnInit, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-custom-dropdown',
templateUrl: './custom-dropdown.component.html',
styleUrls: ['./custom-dropdown.component.scss'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomDropdownComponent),
multi: true,
}]
})
export class CustomDropdownComponent implements OnInit, ControlValueAccessor {
options: string[];
selectedOption: string;
onChange: (_: any) => {};
constructor() { }
ngOnInit() {
this.options = [
'option 1',
'option 2',
'option 3',
];
this.selectedOption = this.options[0];
}
writeValue(value: string) {
this.selectedOption = value;
}
registerOnChange(fn: (_: any) => {}) {
this.onChange = fn;
}
changeSelectedOption(option: string) {
this.selectedOption = option;
this.onChange(option);
}
registerOnTouched() { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment