首页 > 解决方案 > 使用文本框自定义多选 - 使用 contenteditable

问题描述

我正在使用文本框进行自定义多选。如果用户输入 1、2、3、4,那么 1 2 3 4 应该被视为单独的值。我可以使用<input type="text">它而不是我想要 div 的文本框因此用户可以单击 div 中的任何位置并能够添加项目。下图是我当前的实现。 在此处输入图像描述

custom-autocomplete.component.html

<div name="test">
    <ul class="autocomplete-text base-auto-select-cointainer"> 
        <li class="d-inline-flex selected-item" *ngFor="let item of itemList;let i=index" title="{{item}}">{{item}}
            <span class="remove-item pointer" role="presentation" (click)="handelOnItemRemove(i)">×</span></li>
        <li class="d-inline-flex">
            <input class="item-input" type="text"  (keyup)="handelOnItemKeyUp($event)"
                tabindex="0" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false"
                role="textbox">
        </li>
    </ul>
</div>

自定义自动完成组件.ts

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

@Component({
  selector: 'app-custom-autocomplete',
  templateUrl: './custom-autocomplete.component.html',
  styleUrls: ['./custom-autocomplete.component.css']
})
export class CustomAutocompleteComponent implements OnInit {

  itemList: any[] = []; // for collection selcted items
  userInputs: any;
  model = 'some text';
  constructor() { }
  // event emiters for passing data to parent componet.
  @Output() handelItemSelection: EventEmitter<any> = new EventEmitter<any>();
  ngOnInit() {       
  }
  handelOnItemKeyUp(event) {       
    if (event.target.value) {
      let userInput: string = event.target.value;
      let splitChar = userInput.charAt(userInput.length - 1);
      let tempArray: any[] = userInput.split(',');
      if (tempArray.length > 1) {
        if (tempArray[0] != "" && tempArray[0] != undefined) {
          this.itemList.push(tempArray[0])
          this.handelItemSelection.emit(this.itemList); //passing updated items to parent
        }
      }
      console.log('')
      splitChar == ',' ?event.target.value = null : '' // setting empty value to text box when user enter ,
    }
  }
  // code block for handel item removal from list.
  handelOnItemRemove(index: number) {
    this.itemList.splice(index, 1);
    this.handelItemSelection.emit(this.itemList); //passing updated items to parent
  }
}

有人可以建议我如何使用<div contenteditable="true"></div>

标签: javascriptangularmulti-select

解决方案


推荐阅读