0

I am trying to assign a value dynamically to auto-complete but it is not working

HTML

<label for="centerId" class="control-label">Center</label>
                                    <p-autoComplete formControlName="center" id="centerId"  [suggestions]="iCenter" placeholder="Center (required)" (completeMethod)="searchCC($event)" [style]="{'width':'85%'}" [inputStyle]="{'width':'85%'}" field="name" dataKey="id" [dropdown]="true"></p-autoComplete>

interface

export interface ICenter{

   id: string,
   name: string
}

ts

(for field="name" dataKey="id" the value is the same, so id=name)

iCenter: ICenter[];

also confirmed there is a value 
console.log(this.center)
    searchCC(event) {

    this.iCenter = this.iCenter
        .filter(data => data.name.toString()
            .toLowerCase()
            .indexOf(event.query.toString().toLowerCase()) !== -1);

}
 this.ersaForm = this._fb.group({
        center: ['', Validators.required],
    });

 this.ersaForm.patchValue({

            //also tried  center:center
          //also tried center: [itimData.center, itimData.center],
            center: [{ 'field': this.center,'dataKey': this.center}],
            phone: itimData.phone,
            email: itimData.email
        });

***************************************UPDATE***************************************************************** Got it working , here is how

center: {id: itimData.center, name: itimData.center },

4

1 回答 1

3

The properties 'field' and 'dataKey' are not necessarily part of your object.

PrimeNG docs:

field

Field of a suggested object to resolve and display.

dataKey

A property to uniquely identify a value in options.

If your list looks like this:

const items = [
    {id: 1, name: 'Apple'}, 
    {id: 2, name: 'Banana'}, 
    {id: 3, name: 'Pineapple'}
];

Then the property 'field' should refer to 'name' and 'dataKey' to 'id'.

Now if you want to set the value of the autocomplete to 'Pineapple' then patchValue looks like this.

this.form.patchValue({
    item: {
        id: 3, // mandatory
        name: 'Pineapple' // optional
    }
});

The PrimeNG component will search for an object with the id equal to 3. When there is a match he will set the selection to that object.

https://www.primefaces.org/primeng/#/autocomplete

于 2018-09-10T17:49:02.550 回答