角度自定义选择组件:绑定选择的选项

问题描述

我做了一个自定义选择,它会隐藏选择并在选择项目的地方显示一个下拉列表。

但是我无法将下拉菜单中选择的项目绑定到我选择的html元素。

自定义组件html

<div class="select">
  <select class="select-hidden" [(ngModel)]="selectedOption">
    <option *ngFor="let option of data" [value]="option.key">{{option.value}}</option>
  </select>

  <div class="select-styled" (click)="enabletoggle()" [ngClass]="{'active' : toggle}">
    {{selectedOption.value}}
  </div>

  <ul class="select-options" [ngClass]="{'block' : toggle}">
    <li (click)="select(option)" *ngFor="let option of data" >{{option.value}}</li>
  </ul>
</div>

自定义组件TS

import {Component,OnInit,Input} from '@angular/core';

export interface Option {
  key: number;
  value: string;
}

@Component({
  selector: 'alta-select',templateUrl: './alta-select.component.html',styleUrls: ['./alta-select.component.scss'],host: { 'class': 'alta-select' },})
export class AltaSelectComponent implements OnInit {

  @input() data: Option[] = [];
  toggle = false;
  selectedOption: Option;

  enabletoggle = () => this.toggle = !this.toggle;

  select = (actualOption) => {
    this.enabletoggle();
    this.selectedOption = actualOption;
  }

  ngOnInit(): void{
    this.selectedOption = this.data[0];
  }
}

以及如何调用该组件((更改))无效,因为select永不更改值,只有下拉列表有效,这就是我要绑定的值

<alta-select [data]="options" (change)="changeTest($event)"></alta-select>

解决方法

将您的selectedOption声明为输入和输出属性以便与其绑定。

@Input() selectedOption: Option;
@Output() selectedOptionChange = new EventEmitter<Option>();

...

select = (actualOption) => {
    this.enableToggle();
    this.selectedOption = actualOption;
    this.selectedOptionChange.emit(this.selectedOption);
  }

您可以通过进行双向绑定

<alta-select [data]="options" [(selectedOption)]="mySelection"></alta-select>

或者如果您仅对更改事件感兴趣

<alta-select [data]="options" (selectedOptionChange)="changeTest($event)"></alta-select>

还可能需要在自定义选择中更改值绑定。该选项应该是值而不是键。

[value]="option"