【问题标题】:NgPrime p-dropdown Template Advanced with Templating, Filtering and Clear Icon-collapses when wraping with form elementPrimeng p-dropdown Template Advanced with Templating, Filtering and Clear Icon-wraps when wraps with form element
【发布时间】:2021-09-14 11:28:14
【问题描述】:
https://stackblitz.com/edit/primeng-dropdown-demo?file=src%2Fapp%2Fapp.component.html
当我将以下代码包装在 元素中时,drop 会崩溃。
<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>
【问题讨论】:
标签:
javascript
html
angular
primeng-dropdowns
【解决方案1】:
首先使用响应式表单而不是 ngModel
form: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.form = this.fb.group({
country: this.fb.control('')
});
}
模板:
<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>
第二个:不要在pTemplate里面使用*ngIf(其实这是折叠标签的主要问题)
请注意:
- 使用
formControlName 而不是ngModel
- 在
pTemplate 中使用let-item 来获取对所选项目的引用
- 不要忘记将
ReactiveFormsModule 添加到导入中