簡體   English   中英

Primeng 自動完成組件的 Angular2 數據綁定

[英]Angular2 Data binding for Primeng autocomplete component

我正在使用Angular2: 2.1.0Primeng: 1.0.0
我希望Autocomplete組件綁定到我的object's key並在 UI 中顯示object's value

這里的對象是

[{
    "user_id": 101,
    "user_name": "John"
},
{
    "user_id": 101,
    "user_name": "Ganesh"
},
{
    "user_id": 101,
    "user_name": "Irfan"
}]

應用程序組件.html

<p-autoComplete  [(ngModel)]="userId" placeholder="User Search..." field="user_name" [suggestions]="suggestionList"  (completeMethod)="userSearch($event)"></p-autoComplete>

在自動完成中使用field屬性我可以在 UI 屏幕中顯示我的object's value ,但整個對象都綁定到userId
如何將所選對象的user_id綁定到userId

我有同樣的問題,實際上結束使用單獨的方法來捕獲值

captureId(event: any) {
    this.userId = event.user_id;
}

和實際使用

<p-autoComplete (onSelect)="captureId($event)" ...

@NTN-JAVA 我已經使用字段屬性完成了此操作。

 <p-autoComplete [(ngModel)]="userName" [suggestions]="filteredBrands" name="guestType" (completeMethod)="filterBrands($event)" [size]="12" [minLength]="1" field="user_name" inputStyleClass="txt-box" placeholder="Hint: type 'v' or 'f'" [dropdown]="true" (onDropdownClick)="handleDropdownClick($event)"> </p-autoComplete>

 guestDetails = [{ "user_id": 101, "user_name": "John" }, { "user_id": 102, "user_name": "Ganesh" }, { "user_id": 103, "user_name": "Irfan" }] **Javascript** handleDropdownClick() { this.filteredBrands = []; setTimeout(() => { this.filteredBrands = guestDetails; }, 100); }

總結我到目前為止對問題和討論的理解:

  • 自動完成為我們提供了一個 User 作為模型
  • 但我們想要的是 user_id
  • 基本上,我們需要從 User 到 user_id 的“模型映射”,反之亦然(如果我們的模型是用 user_id 初始化的,則應在自動完成中預先選擇相應的 User )

這可以通過包裝自動完成(以及 angular 中的所有其他輸入組件)實現的 ControlValueAccessor 接口以通用方式實現。 這個包裝器可以進行轉換。 然后在包裝器上使用 ngModel、formControl 或 formControlName 指令。

我創建了一個plunkr來展示這種方法。 它使用“國家”而不是“用戶”:

<control-value-mapper [formControl]="control" [toModel]="idOfCountry" [fromModel]="countryForId" >
      <p-autoComplete #cvDelegate

        [suggestions]="results" 
        (completeMethod)="search($event)" 
        field="name"
        dataKey="id">

      </p-autoComplete>
</control-value-mapper>

ControlValueMapper 看起來像這樣:

@Component({
  selector: 'control-value-mapper',
  template: '<ng-content></ng-content>',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => ControlValueMapper),
    multi: true
  }]
})
export class ControlValueMapper implements ControlValueAccessor {
  @ContentChild('cvDelegate')
  delegate: ControlValueAccessor

  @Input()
  fromModel: (any) => any;

  @Input()
  toModel: (any) => any;

  setDisabledState(isDisabled: boolean) {
    this.delegate.setDisabledState(isDisabled);
  }

  writeValue(obj: any) {
    this.delegate.writeValue(this.fromModel(obj));  
  }

  registerOnChange(fn: any)  {
    this.delegate.registerOnChange(value => fn(this.toModel(value)));
  }

  registerOnTouched(fn: any)  {
    this.delegate.registerOnTouched(value => fn(this.toModel(value)));
  }
} 

"toModel" 和 "fromModel" 是從 Country 映射到其 id 的函數,反之亦然。

請注意,此解決方案可能比其他解決方案“更長”,但它可以在所有類似情況下重復使用(使用除自動完成以外的其他輸入組件)。

一年前我找到了一個解決方案,並為其他人更新了我的答案。 作為stefan's回答,我們需要模型映射,但他的回答看起來是一個很大的過程。

我使用了primeng 自動完成組件並使用@Input()@Output()事件創建了一個名為user-search的自己的組件。

模板( user.search.component.html

<p-autoComplete [(ngModel)]="userObject" placeholder="User Search..." field="user_name" [suggestions]="userSuggesstionList"
 (onSelect)="onUserSelect($event)" (completeMethod)="search($event)">
</p-autoComplete>

組件( UserSearchComponent ),

@Component({
    selector: 'user-search',
    templateUrl: 'user.search.component.html'
})
export class UserSearchComponent implements OnInit {
   userSuggesstionList: any[] = [];
    userObject: any;
    constructor(
    ) { }

    ngOnInit() {

    }

    // note that this must be named as the input model name + "Change"
    @Output() userSelected: any = new EventEmitter();
    @Output() userIdChange: any = new EventEmitter();
    @Input()
    set userId(userId: string) {
        if (userId != null && userId != '') {
            this.userObject = // Load user object from local cache / from service.
        } else {
            this.userObject = null;
        }
    }

    get userId(): string {
        if (this.userObject != null) {
            return this.userObject.userId;
        } else {
            return null;
        }
    }

    search(event) {
        // your search logic.
    }

    onUserSelect(event) {
        this.userIdChange.emit(event.userId);
        this.userSelected.emit(event);
    }
}

用戶搜索組件的用法是,

<user-search [(userId)]="user_id"></user-search>

這里將 user_id 作為輸入給user-search組件, user-search組件根據user_id從緩存/服務器加載實際用戶對象。 一旦用戶對象被加載, p-autocomplete將與userObject綁定並在自動完成框中顯示用戶名。

一旦用戶從建議列表中選擇,就會觸發默認更改事件以更新父組件中的user_id值。

你也可以利用 UserObject 即。 {user_id: 'xxx', user_name:'xxx'} 在userSelected事件中。

我們可以簡單地將 primeNG 的自動完成包裝在一個實現ControlValueAccessor接口的自定義自動完成組件中。

自定義組件將自定義數據如果結合dataKey被定義為@Input或保持如果沒有primeNG的默認行為dataKey定義。

在下面的代碼中,我只使用了我需要的屬性和事件,但它可以應用於 primeNG 的 API 提供的所有屬性和事件。

這是 HTML 代碼:

<p-autoComplete (completeMethod)="completeMethod.emit($event)"
                (onClear)="onClear.emit($event)"
                (onDropdownClick)="onDropdownClick.emit($event)"
                (onSelect)="select($event)"
                [dataKey]="dataKey"
                [delay]="delay"
                [disabled]="disabled"
                [dropdown]="dropdown"
                [emptyMessage]="emptyMessage"
                [field]="field"
                [forceSelection]="forceSelection"
                [maxlength]="maxLength"
                [minLength]="minLength"
                [multiple]="multiple"
                [placeholder]="placeholder"
                [readonly]="readonly"
                [required]="required"
                [styleClass]="styleClass"
                [suggestions]="suggestions"
                [unique]="unique"
                [(ngModel)]="autoCompleteValue">
</p-autoComplete>

這是打字稿代碼:

import { Component, EventEmitter, forwardRef, Input, Output } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    selector: 'mb-auto-complete',
    templateUrl: './auto-complete.component.html',
    styleUrls: ['./auto-complete.component.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => AutoCompleteComponent),
            multi: true
        }
    ]
})
export class AutoCompleteComponent implements ControlValueAccessor {

    @Input() dataKey: string = null;
    @Input() delay: number = 300;
    @Input() disabled: boolean;
    @Input() dropdown: boolean = false;
    @Input() emptyMessage: string = null;
    @Input() field: any = null;
    @Input() forceSelection: boolean = null;
    @Input() maxLength: number = null;
    @Input() minLength: number = 1;
    @Input() multiple: boolean = false;
    @Input() placeholder: string;
    @Input() readonly: boolean = false;
    @Input() required: boolean = false;
    @Input() styleClass: string = null;
    @Input() suggestions: any[] = [];
    @Input() unique: boolean = true;
    @Output() completeMethod: EventEmitter<any> = new EventEmitter<any>();
    @Output() onClear: EventEmitter<any> = new EventEmitter<any>();
    @Output() onDropdownClick: EventEmitter<any> = new EventEmitter<any>();
    @Output() onSelect: EventEmitter<any> = new EventEmitter<any>();
    private onChange = (value: any): void => { /**/ };
    private onTouched = (): void => { /**/};
    public autoCompleteValue: any;

    public registerOnChange(fn: any): void {
        this.onChange = fn;
    }

    public registerOnTouched(fn: any): void {
        this.onTouched = fn;
    }

    public setDisabledState(isDisabled: boolean): void {
        this.disabled = isDisabled;
    }

    public writeValue(value: any): void {
        if (this.dataKey?.length > 0) {
            this.autoCompleteValue = this.suggestions.filter((item: any) => item[this.dataKey] === value)[0];
        } else {
            this.autoCompleteValue = value;
        }
    }

    public select(selectedValue: any): void {
        const newValue: any = this.dataKey?.length > 0 ? selectedValue[this.dataKey] : selectedValue;
        this.onSelect.emit(newValue);
        this.onChange(newValue);
    }
}

然后你可以使用你的自定義組件,在你使用<p-autoComplete ..>任何地方你都可以用<mb-autoComplete ..>替換它(當然除了在AutoCompleteComponent的 html 中你必須保留<p-autoComplete ..> )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM