Create placeholder in nz-select

Viewed 17

Here is my code:

<div nz-col [nzSpan]="6">
      <nz-form-item class="form-item">
        <nz-form-label nzRequired="" [nzNoColon]="true">Loại hàng hóa
        </nz-form-label>

        <nz-select nzShowSearch="true" formControlName="category" (ngModelChange)="changeCategory($event)">
          <nz-option *ngFor="let item of CategoryList " nzValue="{{item.code}}" nzLabel="{{item.name}}">
          </nz-option>
        </nz-select>
      </nz-form-item>
    </div>

File ts:

// take data from api
 let res = await this.manageDocument.searchDetail(this.id);

if (res.msg == MESSAGE.SUCCESS) {category: res.data.CategoryName,}

I want the will display the category name (res.data.CategoryName) taken from api as placeholder using FormControlName (=category) instead of [(ngModel)] but i don't know how to do that. Thanks

1 Answers

Here is a working example for nz-select please compare the stackblitz with your code and try to modify it to suit your requirements!

service

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { of } from 'rxjs/observable/of';
import { delay } from 'rxjs/operators';

@Injectable()
export class TestService {
  constructor() {}

  getCategory(): Observable<any> {
    // simulating an api call
    return of({
      msg: 'success',
      data: {
        CategoryName: 'AAA',
        mark: 'AAA',
        age: 18,
        sex: 'male',
      },
    }).pipe(delay(1000));
  }
}

ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { TestService } from './test.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  testForm: FormGroup;
  name = 'The nz-select show nothing when i set customerObj in ngOnInit';
  customers: Array<any> = [
    {
      CategoryName: 'AAA',
      mark: 'AAA',
      age: 18,
      sex: 'male',
    },
    {
      CategoryName: 'BBB',
      mark: 'BBB',
      age: 19,
      sex: 'male',
    },
    {
      CategoryName: 'CCC',
      mark: 'CCC',
      age: 20,
      sex: 'female',
    },
  ];

  constructor(private fb: FormBuilder, private testService: TestService) {
    this.testForm = this.fb.group({
      category: '',
    });
  }
  ngOnInit() {
    this.testService.getCategory().subscribe((res) => {
      if (res.msg == 'success') {
        this.testForm.patchValue({ category: res.data.CategoryName });
      }
    });
  }
}

html

<h1>{{ name }}</h1>
<form [formGroup]="testForm">
  <nz-select
    style="width: 200px;"
    nzAllowClear
    formControlName="category"
    [nzShowSearch]="true"
  >
    <nz-option
      *ngFor="let option of customers"
      [nzLabel]="option.CategoryName"
      [nzValue]="option.CategoryName"
    >
    </nz-option>
  </nz-select>
</form>

forked stackblitz

Related