我在我的angular5应用程序中使用PrimeNG。我对p-dropdown有疑问



我有显示国家的p下拉列表。我正确地绑定了选择选项,在那里它可以正常工作(此数据来自api),但是我需要将此p下拉列表的默认选择选项设置为“印度”。

我将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>


我的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 });
        }
    }
 });

最佳答案

尝试更换

this.applicant.country = 'India';




this.applicant = {country: 'India'};


编辑

从API获取数据后,显示p-dropdown

<div *ngIf="dataLoaded">
  <p-dropdown [options]="countries" [(ngModel)]="applicant.country"></p-dropdown>
</div>


Plunker

10-06 00:32