Search code examples
javascriptangularangular-ngselect

ng-select with NGFORM facing rendering issue


Below is my HTML code, this is where I am trying to use ng-select directive as found some where during internet search. As I am not having expertise with me on ng I am not sure why the list is not showing on the screen.

<form #f="ngForm" (ngSubmit)="saveProfile()"> 
<div class="form-body">
   <h4 class="form-section"><i class="la la-eye"></i> About User</h4>
   <div class="row">
   </div>
   <div class="col-md-6">
      <div class="form-group">
         <label for="userinput3">City Selection</label>
         <ng-select [items]="singleSelectArray" [searchable]="true" bindLabel="item_text" placeholder="Select city"
         [(ngModel)]="singlebasicSelected" >
         </ng-select>
      </div>
   </div>
</div>
</form>

Here is my TYPESCRIPT File trying to populate city list from server, but in this case I did hard coded from TS file and send to HTML page

export class UserProfileComponent implements OnInit {
  @ViewChild('f', { read: true }) userProfileForm: NgForm;
  private profileInfo: DashBoardData.ProfileInfo;
  model: any = {};
  profileInfoFormGroup: FormGroup;
  singleSelectArray = selectData.singleSelectArray;
  cityLoading = false;
  matchedResultArray: City[] = [];

  constructor(
    private formBuilder: FormBuilder,
    private dataService: NgSelectDataService) { }

  loadCity() {
    this.cityLoading = true;
    this.dataService.getPeople().subscribe(x => {
      this.matchedResultArray = x;
      this.cityLoading = false;
    });
  }

  ngOnInit() {
    this.loadCity();
  }
}

But while rendering on the browser I am getting following error to the ng-select component enter image description here


Solution

  • Angular does not have a built-in ng-select component. Most likely, you found a piece of this third-party library on the internet. However, in order to make a drop-down list, it is not needed. You can just use the native browser elements: select and option.

    <select [(ngModel)]="selectedOption">
      <option *ngFor="let option of options" [value]="option.value">
        {{ option.title }}
      </option>
    </select>
    

    I've created an example on stackblitz.

    But if you need a more complex dropdown list, for example with a search function, you can install and use this library that I mentioned above.