Home > other >  How to get bindlabel value from angular ng-select
How to get bindlabel value from angular ng-select

Time:10-25

I am using angular ng-select when the user types I would like to have the value and when the user wants to create a new brand I would like to have the writeen value in backend and frontend. This is my code so far my issue is that the val is undefined how can I get the written value Thank you for your help

  <ng-select placeholder="{{'HtmlElement.DropDownNoSelected' | translate}}"
             [items]="brands"
             bindLabel="brandName"
             bindValue="brandId"
             id="brandId"
             name="brandId"
             formControlName="brandId"
             (change)="brandTyped()"
             (keydown)="brandTyped()" (keyup)="brandTyped()">
    <ng-template ng-footer-tmp>
      <p  (click)="CreateNewBrand()">Create New {{TEXT_VALUE}} </p>
    </ng-template>
  </ng-select>


brandTyped(val) {
    console.log("You typed new brand "   val)
}

CreateNewBrand(val) {
    console.log("You createed new brand "   val)
}

CodePudding user response:

If I understand you correctly, I think you're looking for the (search) event of ng-select (see Doc link at the bottom).

The (search) event will emit an object value of the search term in the textfield and the matching items for that search term. An example of the event emitted will looking something like this...

{
  "term": "vil",
  "items": [
    {
      "id": 1,
      "name": "Vilnius"
    },
    {
      "id": 3,
      "name": "Pavilnys",
      "disabled": true
    }
  ]
}

You can bind to this event to get the search term the user search.

<ng-select [items]="cities2"
  bindLabel="name"
  bindValue="id"
  placeholder="Select cities"
  [(ngModel)]="selectedCityIds"
  (search)="onSearchChange($event)">
</ng-select>
public onSearchChange(value: any): void {
  // HANDLE SEARCH TERM CHANGES HERE...
  this.searchTerm = value;
}

See Stackblitz below of a working example.

Edit

You can assign the search term object in your TS file and use that to render the value in the dropdown. See updated stackblitz for an example.

<ng-select 
  [items]="cities2"
  bindLabel="name"
  bindValue="id
  placeholder="Select cities"
  [(ngModel)]="selectedCityIds"
  (search)="onSearchChange($event)"
>
  <ng-template ng-footer-tmp>
    <p  (click)="CreateNewBrand()">
      Create New {{searchTerm?.term}}
    </p>
  </ng-template>
</ng-select>
  • Related