angular - PrimeNg 自动完成在清除时发送空字符串

标签 angular autocomplete primeng

我有一个 p-autocomplete 元素 (primeng 7.0.5),它控制自定义对象字段(类型 OrganizationView)。

这是标记:

<p-autoComplete
    [(ngModel)]="state.organization"
    (completeMethod)="onSearchOrganisation($event)"
    (onClear)="state.organization = null"
    (onSelect)="onOrganizationSelected($event)"
    [emptyMessage]="'GLOBALS.NORESULT' | translate"
    [forceSelection]="true"
    [suggestions]="availableOrganizations"
    [dropdown]="true"
    field="name"
    placeholder="{{'PLACEHOLDERS.ORGANISATION' | translate}}">

state.organization 使用以下代码触发 setter:

set organization(newOrganization: OrganizationView) {
    this._organization = newOrganization;
    console.log(typeof newOrganization, newOrganization);
  }

从自动完成中选择值时,我总是会按预期获得 OrganizationView 对象。清除字段时出现问题:

清除时(用鼠标选择全部并按退格键),我的 setter 被触发两次:第一次为空,第二次为空字符串。这是 console.log 输出:

> object null
> string 

字符串的插入让我担心,因为它弄乱了我尝试设置的整个强类型系统。我可以为空字符串编写显式检查,但我想知道是否有更干净的解决方案,或者我是否出错了。

最佳答案

我遇到了同样的问题并使用了此解决方法:

set organization(newOrganization: OrganizationView) {
    this._organization = newOrganization ? newOrganization : <OrganizationView>{};
    console.log(typeof newOrganization, newOrganization);
  }

关于angular - PrimeNg 自动完成在清除时发送空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55237957/

相关文章:

angular - Primeng 的 'selectedItem' 模板不起作用,它始终将所选值设置为在自动完成中设置的 'field' 属性

angular - 如何覆盖 primeng 组件的样式?

angular - 如何显示 ts 表中的图像

javascript - Angular ngx-mat-select-search 自定义组件

google-chrome-extension - Google Chrome 扩展程序 - 如何从热门网站列表中删除条目(多功能框建议)?

jquery自动完成显示id而不是标签

html - 带有 PrimeNG 的 Angular 2 嵌套模态对话框不起作用

angular - 等待2个方法完成Angular 6

angular - 对象可能为 Null

android - 使用带有 ArrayAdapter<Objects> 而不是 ArrayAdapter<Strings> 的 Android AutoCompleteTextView