我用JS创建了一个自定义选择器系统,试图使其看起来更好。它看起来很完美,并且可以在我看到选择器时对其进行更改,但它不会更改Angular组件上的ngModel,从而使它保持未定义状态。这是我的JS和HTML。
<div class="form__select">
<select id="gender" name="gender" #gender="ngModel" [(ngModel)]="user.occupation">
<option value="0">Selecciona un género</option>
<option value="1">Hombre</option>
<option value="2">Mujer</option>
<option value="3">Otro</option>
</select>
</div>
load_selector() {
const selectors: HTMLCollectionOf<Element> = document.getElementsByClassName("form__select");
document.addEventListener("click", MainScript.close_selector);
[].forEach.call(selectors, (selector) => {
const select: any = selector.getElementsByTagName("select")[0];
let replaced: HTMLElement = document.createElement("DIV");
replaced.setAttribute("class", "form__select-box");
replaced.innerHTML = select.options[select.selectedIndex].innerHTML;
selector.appendChild(replaced);
let option_parent: HTMLElement = document.createElement("DIV");
option_parent.setAttribute("class", "form__select-items");
[].forEach.call(select.options, (options) => {
let option: HTMLElement = document.createElement("DIV");
option.setAttribute("class", "form__select-item");
option.innerHTML = options.innerHTML;
option.addEventListener("click", function () {
const parent_node: any = (<HTMLElement>(<HTMLElement>(<HTMLElement>this.parentNode)).parentNode).getElementsByTagName("select")[0];
let previous_sibling: any = this.parentNode.previousSibling;
for (let i = 0; i < parent_node.length; i++) {
if (parent_node.options[i].innerHTML == this.innerHTML) {
parent_node.selectedIndex = i;
previous_sibling.innerHTML = (<HTMLElement>this).innerHTML;
let actual_selected = (<HTMLElement>(<HTMLElement>this.parentNode)).getElementsByClassName("form__select-item--selected");
[].forEach.call(actual_selected, (node) => {
node.classList.remove("form__select-item--selected");
node.classList.add("class", "form__select-item");
});
this.classList.add("form__select-item--selected");
}
}
previous_sibling.click();
});
option_parent.appendChild(option);
});
selector.appendChild(option_parent);
replaced.addEventListener("click", function (e) {
e.stopPropagation();
(<any>this).nextSibling.classList.toggle("form__select-items--active");
(<any>this).classList.toggle("form__select-box--active");
});
});
}