Bha*_*nde 11 primeng primeng-dropdowns angular5
我在angular5应用程序中使用PrimeNG.我有p-dropdown的问题
题
我有显示国家的p-down.我正确绑定选择选项,它工作正常(此数据来自api),但我需要为此p-dropdown设置默认选择选项为"India".
我将ng-model值设置为印度,但它不起作用.
我的dummy.component.html代码
<div class="form-group col-md-2">
<div>
<label for="inputEmail4"> Select Country</label>
<span style="color:red">*</span>
</div>
<p-dropdown name="country" [options]="countries" [(ngModel)]="applicant.country" placeholder="select country"
(onChange)="getStatebyCountry(applicant.country,$event)" #country="ngModel" required>
</p-dropdown>
<span *ngIf="country.invalid && (country.dirty || country.touched)">
<span [hidden]="!country.hasError('required')" style="color:#ffa500">country is mandatory</span>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
我的dummy.component.ts
export class dummyComponent implements OnInit {
//variable declaration scope for all controller function
applicant: any = {};
country: string; constructor() {
}
ngOnInit() {
this.applicant.country = 'India';
}
this.countries = [];
// this.countries.push({ label: 'Select Country', value: '' });
//getallcountries
this.UserService.getallcountries().subscribe(result => {
console.log("countries" + result);
this.cnt = result;
for (let i = 0; i <= this.cnt.length; i++) {
if (this.cnt[i].id === 1) {
this.countries.push({ label: this.cnt[i].name, value: this.cnt[i].id });
}
}
});
Run Code Online (Sandbox Code Playgroud)
小智 14
如果 PrimeNG 不知道将“selectedCountry”绑定到哪个字段,则可能会导致这种情况,即。您的下拉控件的“国家/地区”模型具有更多的键和值属性。
就我而言,我必须明确地“告诉”每个下拉字段的值的属性是"value". 我p-dropdown dataKey为此使用了该属性。
因此,在我的下拉控件中,我添加了如下内容:
<p-dropdown dataKey="value" ></p-dropdown>
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读更多内容。
尝试更换
this.applicant.country = 'India';
Run Code Online (Sandbox Code Playgroud)
和
this.applicant = {country: 'India'};
Run Code Online (Sandbox Code Playgroud)
编辑
p-dropdown从 API 获取数据后显示您的信息。
<div *ngIf="dataLoaded">
<p-dropdown [options]="countries" [(ngModel)]="applicant.country"></p-dropdown>
</div>
Run Code Online (Sandbox Code Playgroud)
您可以使用 ngModel设置PrimeNG Dropdown的默认值,如下所示:
组件.html:
<p-dropdown [options]="cities" name="selectedCity" [(ngModel)]="selectedCity"></p-dropdown>
Run Code Online (Sandbox Code Playgroud)
组件.ts:
selectedCity: string = 1; //Id value of the City to be selected
Run Code Online (Sandbox Code Playgroud)
如果由于版本问题未修复,请尝试以下操作:
this.cities.value = this.selectedCity;
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助...
| 归档时间: |
|
| 查看次数: |
27265 次 |
| 最近记录: |