如何使用打字稿切片字符串的一部分?

时间:2018-08-23 11:20:13

标签: javascript angular typescript autocomplete

我正在建立一个带有多个选择的自定义选择框,就像角形材料芯片一样。

HTML

<div class="autocomplete">
    <div class="chips-input-container">
        <div class="col-md-4">
            <div class="user-chip" *ngFor="let user of userSelects">
                {{user.name}}
                <span (click)="deleteSelects(user)" class="delete-icon-chip">&#10006;</span>
            </div>
        </div>

        <div class="col-md-4 form-label-group">
            <input name="suggestion" type="text" id="autocomplete-input" class="form-control" placeholder="User" (click)="suggest()"
             [(ngModel)]="userSelectsString" (keyup)="onKey($event)" id="autocomplete-input">
            <label for="autocomplete-input" class="emailBox"></label>
            <label class="fa fa-caret-down input-icon"></label>
        </div>
    </div>

    <ul id="autocomplete-results" class="autocomplete-items" *ngIf="show">
        <li *ngFor="let s of suggestions" [ngClass]="isSelected(s) ? 'selected-suggestion' : ''" (click)="selectSuggestion(s)">{{ s.name }}</li>
    </ul>
</div>

TS:

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
   suggestion: string = '';
  typeahead: FormControl = new FormControl();
  openSelectBox: boolean = false;

  fieldHistory: string[] = [];

  inputValue: string;
  autocomplete_results: any;
  input = document.querySelector('#autocomplete-input');
  userSelectsString = '';
  name = 'Angular';
  userSelects = [];
  suggestions = [{"id":"001","name":"mango"},{"id":"002","name":"apple"},{"id":"003","name":"banana"},{"id":"004","name":"pine"},{"id":"005","name":"orange"},{"id":"006","name":"chery"},{"id":"007","name":"watermelon"},{"id":"008","name":"grapes"},{"id":"009","name":"lemon"}];

  show: boolean = false;

  suggest() {
    this.show = true;
  }

  isSelected(s:any) {
   return this.userSelects.findIndex((item) => item.id === s.id) > -1 ? true : false;
  }

  selectSuggestion(s) {
    this.userSelects.find((item) => item.id === s.id) ? 
    this.userSelects = this.userSelects.filter((item) => item.id !== s.id) :
    this.userSelects.push(s);
    this.show = false;
  }

  deleteSelects(s) {
    this.userSelects = this.userSelects.filter((item) => item.id !== s.id);
  }

  assignToNgModel() {
    this.userSelectsString = '';
    this.userSelects.map((item) => this.userSelectsString += item.name + ' ');
  }

  onKey(e) {
    this.inputValue = e.target.value;

    if (this.inputValue.length > 0) {
      var people_to_show = [];

      this.autocomplete_results = document.getElementById("autocomplete-results");
      this.autocomplete_results.innerHTML = '';
      people_to_show = this.autocomplete(this.inputValue);

      for (let i = 0; i < people_to_show.length; i++) {
        this.autocomplete_results.innerHTML += '<li>' + people_to_show[i] + '</li>';
      }
      this.autocomplete_results.style.display = 'block';
    } else {
      people_to_show = [];
      this.autocomplete_results.innerHTML = '';
    }
  }

  autocomplete(val) {
    var people_return = [];
    for (let i = 0; i < this.suggestions.length; i++) {
      if (val === this.suggestions[i].slice(0, val.length)) {
        people_return.push(this.suggestions[i]);
      }
    }
    return people_return;
  }
}

截至选择和删除部分,一切正常,但是当我实现自动完成功能时,由于使用切片对象数组而无法获得结果。

我的数据是:

  suggestions = [{"id":"001","name":"mango"},{"id":"002","name":"apple"},{"id":"003","name":"banana"},{"id":"004","name":"pine"},{"id":"005","name":"orange"},{"id":"006","name":"chery"},{"id":"007","name":"watermelon"},{"id":"008","name":"grapes"},{"id":"009","name":"lemon"}];

在for循环中,由于类型'{“ id”:string;中不存在属性'slice',我遇到了错误。 “ name”:字符串; }”。this.suggestions[i].slice(0, val.length)

  for (let i = 0; i < this.suggestions.length; i++) {
      if (val === this.suggestions[i].slice(0, val.length)) {
        people_return.push(this.suggestions[i]);
      }
    }

如果我在suggestions: any = [{"id":"001","name":"mango"},...}]内给出任何内容,则表明slice不是函数。

请帮助我实现自动完成的结果。

Stackblitz: https://stackblitz.com/edit/angular-euuvxw

2 个答案:

答案 0 :(得分:2)

您可能想切片名称,而不是整个建议对象。看一下如何使用结果,您可能也希望仅将名称推入people_return中:

for (let i = 0; i < this.suggestions.length; i++) {
  if (val === this.suggestions[i].name.slice(0, val.length)) {
  //                              ^^^^
    people_return.push(this.suggestions[i].name);
  }
}

答案 1 :(得分:0)

您需要在数组类型值中使用slice()。您的情况是this.suggestions,所以请使用this.suggestions.slice(0, val.length)