如何在 Angular 7 中将初始值和验证设置为 ng 自动完成?

Posted

技术标签:

【中文标题】如何在 Angular 7 中将初始值和验证设置为 ng 自动完成?【英文标题】:How to set initial value and validation to ng auto-complete in Angular 7? 【发布时间】:2019-10-03 17:59:39 【问题描述】:

在我的项目中,我想进行验证并将初始值设置为自动完成。假设:如果用户没有在自动完成框中选择任何内容,我们应该显示验证错误:“请选择国家/地区”。

代码:

<div style="text-align:center">
  <h1>
    Angular autocomplete
  </h1>
  <img  
       src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>

<div class="ng-autocomplete">
  <ng-autocomplete
    [data]="countries"
    [searchKeyword]="keyword"
    placeHolder="Enter the Country Name"
    (selected)='selectEvent($event)'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocused($event)'
    historyIdentifier="countries"
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
  </ng-autocomplete>

  <ng-template #itemTemplate let-item>
    <a [innerhtml]="item.name"></a>
  </ng-template>

  <ng-template #notFoundTemplate let-notFound>
    <div [innerHTML]="notFound"></div>
  </ng-template>
</div>

component.ts:

import  Component  from '@angular/core';

@Component(
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
)
export class AppComponent  
  keyword = 'name';
  public countries = [
    
      id: 1,
      name: 'Albania',
    ,
    
      id: 2,
      name: 'Belgium',
    ,
    
      id: 3,
      name: 'Denmark',
    ,
    
      id: 4,
      name: 'Montenegro',
    ,
    
      id: 5,
      name: 'Turkey',
    ,
    
      id: 6,
      name: 'Ukraine',
    ,
    
      id: 7,
      name: 'Macedonia',
    ,
    
      id: 8,
      name: 'Slovenia',
    ,
    
      id: 9,
      name: 'Georgia',
    ,
    
      id: 10,
      name: 'India',
    ,
    
      id: 11,
      name: 'Russia',
    ,
    
      id: 12,
      name: 'Switzerland',
    
  ];
    selectEvent(item) 
    // do something with selected item
  

  onChangeSearch(search: string) 
    // fetch remote data from here
    // And reassign the 'data' which is binded to 'data' property.
  

  onFocused(e) 
    // do something
  

查看完整项目链接:https://stackblitz.com/edit/angular-ng-autocomplete

【问题讨论】:

验证并设置初始值?你的意思是什么? 您可以在html的ng-autocomplete元素中使用initialValue='India'设置初始值。但是您打算进行什么验证? 你可以使用 [ngModel] stackbiz @Arul 如果用户没有选择任何我想显示的错误,例如“请选择国家/地区”。我的意思是表单验证 @Alex Char 如何获得价值反应形式?我不想使用 ngmodel。请帮帮我 【参考方案1】:

我遇到了类似的问题。我必须在 http 调用的 subscribe() 中设置 ng-autocomplete 的值。 我在 .ts 文件中声明了我的自动完成功能: @ViewChild('aziendaAutocomplete') aziendaAutocomplete: any; 然后我设置初始值和输入值:

this.aziendaAutocomplete.initialValue = this.aziendeList[0]?.FirmName;
this.aziendaAutocomplete.searchInput.nativeElement.value = this.aziendeList[0]?.FirmName;

在我的情况下,keyword='FirmName' 有效!

           <div class="ng-autocomplete">
            <ng-autocomplete
              #aziendaAutocomplete
              id="aziendaAutocompleteID"
              [data]="aziendeList"
              placeHolder="Cerca un produttore..."
              [searchKeyword]="keyword"
              (selected)='selectEvent($event)'
              (inputChanged)='onChangeSearch($event)'
              (inputCleared)="onClearSearch()"
              [itemTemplate]="itemTemplate"
              [notFoundTemplate]="notFoundTemplate"
              minQueryLength="3"
              [notFoundText]="notFoundText">
            </ng-autocomplete>
            <input type="number" formControlName="azienda" style="visibility: hidden"/>
            <div *ngIf="submitted && formParamsControl.azienda.errors" [ngClass]="(submitted && formParamsControl.azienda.errors) ? 'invalid-feedback d-block' : '' ">
              <div *ngIf="formParamsControl.azienda.errors.required">Selezionare il produttore</div>
            </div>

            <ng-template #itemTemplate let-item>
              <a [innerHTML]="item.FirmName"></a>
            </ng-template>

            <ng-template #notFoundTemplate let-notFound>
              <div [innerHTML]="notFoundText"></div>
            </ng-template>
          </div>

【讨论】:

【参考方案2】:

您可以更改 selectEvent() 中的布尔值,该布尔值会在每次选择选项时触发。我做了一个StackBlitz 的例子只是为了澄清,你可以玩弄自己的行为。 编辑:This StackBlitz 按照 cmets 中的要求使用反应形式。

【讨论】:

【参考方案3】:

要设置初始值,设置[searchKeyword]="initialValue":

initialValue:string = 'India'

<ng-autocomplete
    [data]="countries"
    [searchKeyword]="initialValue"
    [initialValue]="initialValue"
    placeHolder="Enter the Country Name"
    (selected)='selectEvent($event)'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocused($event)'
    historyIdentifier="countries"
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
</ng-autocomplete>

检查有效性 在单击submit 按钮时,使用span 显示错误消息并将其隐藏。如果modelvalue为null,则显示它

HTML

<ng-autocomplete
    [data]="countries"
    [searchKeyword]="initialValue"
    [initialValue]="initialValue"
    placeHolder="Enter the Country Name"
    (selected)='selectEvent($event)'
    (inputChanged)='onChangeSearch($event)'
    (inputFocused)='onFocused($event)'
    historyIdentifier="countries"
    [itemTemplate]="itemTemplate"
    [notFoundTemplate]="notFoundTemplate">
</ng-autocomplete>
    <span class="help-block warning-block" id="invalid-country" *ngIf="showCountryErrorMessage">Please select the country</span>

TS

showCountryErrorMessage:boolean:false

selectEvent(item:any) 
  this.selectedCountry = item


onSubmit()
  if(this.selectedCountry)
     // api call to save data
   else 
    this.showCountryErrorMessage = true;
  

【讨论】:

【参考方案4】:

<div class="ng-autocomplete">

  <ng-autocomplete [data]="data" [searchKeyword]="keyword" (selected)='selectEvent($event)'
      (inputChanged)='onChangeSearch($event)' (inputFocused)='onFocused($event)' [itemTemplate]="itemTemplate"
      [notFoundTemplate]="notFoundTemplate"   formControlName="fname">
  </ng-autocomplete>

  <ng-template #itemTemplate let-item>
      <a [innerHTML]="item.name"></a>
  </ng-template>

  <ng-template #notFoundTemplate let-notFound>
      <div [innerHTML]="notFound"></div>
  </ng-template>
</div>

【讨论】:

以上是关于如何在 Angular 7 中将初始值和验证设置为 ng 自动完成?的主要内容,如果未能解决你的问题,请参考以下文章

如何在Angular2中将输入设置器指定为可选?

如何在 jQuery 日历或 Angular Js 日历中将当前周末日期设置为默认日期。星期在星期日结束

在Angular 6模板语句中将字符串转换为Typescript枚举

在 Angular 7 中将 Json 转换为对象

在javascript中将数字转换为数组| angular7的打字稿[重复]

如果在 Angular 中将 sourcemap 设置为 false 会发生啥