10

I'm working with ng-select in my angular form ( https://github.com/ng-select/ng-select) the code that I'm using :

<ng-select
            formControlName="model"
            name="model"
            id="add_sheet_model"
            [items]="modelItems"
            [multiple]="false"
            [searchable]="false"
            bindLabel="value"
            bindValue="id"
            placeholder="select model"
          >
          </ng-select>

the problem is that the placeholder is not displayed when I put [multiple] = "false" but when I put [multiple] = "true" the placeholder is displayed and I don't want my ngselect to be multiple.

Ps: I'm working with angular 10 and ngselect 5.0.3.

Any idea ?

youssef elhayani
  • 625
  • 8
  • 28

3 Answers3

18

I found the solution finally, it's not in relation to the [multiple] attribute but the way to initialize my FormGroup, this is how I initiated it:

model: new FormControl('', [Validators.required]),

well it should be like this :

model: new FormControl(null, [Validators.required]),

this issue helped me to solve this problem https://github.com/ng-select/ng-select/issues/653

youssef elhayani
  • 625
  • 8
  • 28
6

I had a similar problem, and when I started the page, the ng-select input showed an x ​​in the right corner. Like that:

enter image description here

This occurred to me because the variable with formControlName or [(ngModel)] was initializing with a value. Like that:

*With ngModel:

nameExample = '';

*With formControlName:

editForm = this.fb.group({
   nameExample: [''],
});

The correct way was like that:

*With ngModel:

nameExample?: string;

*With reactive Form:

editForm = this.fb.group({
   nameExample: [null],
});

An example in html would look something like this:

*With ngModel:

<ng-select class="custom" id="field_exemplo" name="nameExample" 
    appearance="outline" [trackByFn]="trackById" [items]="listNameExamples!" 
    [(ngModel)]="nameExample" bindValue="id" bindLabel="name" 
    [placeholder]="'APP_TITLE | translate">
</ng-select>

*With reactive Form:

<ng-select class="custom" id="field_exemplo" name="nameExample" 
    appearance="outline" [trackByFn]="trackById" [items]="listNameExamples!" 
    formControlName="nameExample" bindValue="id" bindLabel="name" 
    [placeholder]="'APP_TITLE | translate">
</ng-select>
Bùi Đức Khánh
  • 3,975
  • 6
  • 27
  • 43
Johnatan Brayan
  • 171
  • 2
  • 4
1

If you are using [(ngModel)]="selectedAnything" in the HTML then on the ts file initialise with

this.selectedAnything: any = [];
vimuth
  • 5,064
  • 33
  • 79
  • 116