防止Angular将输入文本转换回原始值

时间:2020-04-14 04:40:28

标签: jquery angular twitter-bootstrap

我想允许用户输入或选择bootstrap typeahead下拉菜单。如果用户键入文本而对输入元素失去关注(触发模糊事件),它将查找国籍列表的描述,并使用jquery更新输入文本。例如country1-> Country1

现在,当我键入country1并触发模糊事件时,它会转换为Country1,但会再次将其转换为country1。有什么办法可以防止这种情况?

这是我的角度代码。

组件

  // Data
  userdata={nationality:undefined};
  countryData=[{id:0, description:"Country0"}, {id:1, description:"Country1"}, {id:2, description:"Country2"}];

  // Bootstrap typeahead
  searchCountry = (text$: Observable<string>) =>
    text$
      .debounceTime(200)
      .distinctUntilChanged()
      .map(term => term.length < 2 ? []
        : this.countryData.filter(nationality => nationality.description.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 15));
  nationalityFormatter = (nationality) => nationality.description;


  // Blur event
  $onBlur() {
    let domElement = $('#my_company_country_description');

    if (domElement) {
      this.userdata.nationality = this.getCountry(domElement, this.countryData);
    }
  }

  // Check the input text (case insensitive)
  getCountry(company_country: JQuery<HTMLElement>, countries: any[]) {
    for (let i = 0; i < countries.length; i++) {
      let str: any = company_country.val();
      if (str && countries[i].description.toLowerCase() === str.toLowerCase()) {
        return JSON.parse(JSON.stringify(countries[i]));
      }
    }

    company_country.val("");
    return undefined;
  }

HTML

        <input id="my_company_country_description" (blur)="$onBlur()" type="text" class="form-control "
          [(ngModel)]="userdata.nationality" [ngbTypeahead]="searchCountry" name="nationality" #nationality="ngModel"
          [inputFormatter]="nationalityFormatter" [resultFormatter]="nationalityFormatter" [editable]='false'
          placeholder="" required />

0 个答案:

没有答案