0

https://stackblitz.com/edit/primeng-dropdown-demo?file=src%2Fapp%2Fapp.component.html

When i wrap the following code in </form element, the drop collapses.

<h5>Advanced with Templating, Filtering and Clear Icon</h5>
<p-dropdown [options]="countries" [(ngModel)]="selectedCountry" optionLabel="name" [filter]="true" filterBy="name"
    [showClear]="true" placeholder="Select a Country">
    <ng-template pTemplate="selectedItem">
        <div class="country-item country-item-value" *ngIf="selectedCountry">
            <div>{{selectedCountry.name}}</div>
        </div>
    </ng-template>
    <ng-template let-country pTemplate="item">
        <div class="country-item">
            <div>{{country.name}}</div>
        </div>
    </ng-template>
</p-dropdown>

enter image description here

user2435182
  • 47
  • 1
  • 10

1 Answers1

0

first of all use Reactive forms instead of ngModel

  form: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.form = this.fb.group({
      country: this.fb.control('')
    });
  }

template:

<form ngForm="form">
    <h5>Advanced with Templating, Filtering and Clear Icon</h5>
    <p-dropdown [options]="countries" [formControlName]="country" optionLabel="name" [filter]="true" filterBy="name"
        [showClear]="true" placeholder="Select a Country">
        <ng-template pTemplate="selectedItem" let-item>
            <div class="country-item country-item-value">
                <div>{{item.name}}</div>
            </div>
        </ng-template>
        <ng-template let-country pTemplate="item">
            <div class="country-item">
                <div>{{country.name}}</div>
            </div>
        </ng-template>
    </p-dropdown>
</form>

and the second one: do not use *ngIf inside of pTemplate (actually this is the main issue of collapsed label) Notice please:

  • use formControlName instead of ngModel
  • use let-item inside of pTemplate to get the reference to selected item
  • do not forget to add ReactiveFormsModule to imports
icekson
  • 363
  • 1
  • 3