Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

angular5 - How to set default value for PrimeNG p-dropdown

I am using PrimeNG in my angular5 app. I have issue with p-dropdown

Question

I have p-dropdown for showing countries. I bind the select options correctly there it works fine (this data coming from api), but I need to set default selected option for this p-dropdown as "India".

I set up ng-model value as India but it didn't work.

my dummy.component.html code

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

my 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 });
        }
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This may be caused if PrimeNG doesn't know to which field to bind the "selectedCountry", ie. your "countries" model for the dropdown control has more then key and value properties.

In my case, I had to explicitly "tell" to each dropdown field that the property for values is "value". I used the p-dropdown dataKey property for this.

So, in my dropdown control, I added something like this:

<p-dropdown dataKey="value" ></p-dropdown>

You can read more here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...