Set a default value for Angular chain dropdown

[亡魂溺海] 提交于 2019-12-08 15:06:55

问题


I had JSON country within ID, and what I want to is the defeulat value is set to selected, here my select code so far:

<select (change)="onNationalitySelected($event.target.value)" id="nationality" formControlName="nationality">
                <option value=""> {{'messages.dropdownselect' | translate}} </option>
                <option *ngFor="let country of countries" [value]="country.id" [selected]="country.id == '100'" >
                  {{ country.name }}
                </option>
              </select>

.ts file

  onNationalitySelected(nationalityId: number) {
    this.customer.coid = nationalityId;
    this.customer.nationality = this.countries.filter(
      c => (c.id == nationalityId)
    )[0].name;

I tried to set a default value for country is 100, but it's not working, the value still empty after saved to DB.

Thanks for any comments.


回答1:


ts

// Let's use FormGroup so we can add a control/default
countryForm: FormGroup;

// define our countries data
countries = [{
 id: '100',
 name: 'USA',
 code: 'USD'
},
{
 id: '200',
 name: 'Canada',
 code: 'CAD'
},
{
 id: '300',
 name: 'UK',
 code: 'GBP'
}];

constructor(private fb: FormBuilder) {}

ngOnInit() {
 // set country code 100 as default
 this.countryForm = this.fb.group({
  countryControl: [this.countries[0].id]
 });
}

html

// ngValue allows us to use an object for default value assignment
<option [ngValue]="country.id" *ngFor="let country of countries">{{country.name}}</option>

I'm a little uncertain about countryControl: [this.countries[0].id], if it doesn't work, try this instead: countryControl: [this.countries[0]]

Let me know how it goes!



来源:https://stackoverflow.com/questions/57613610/set-a-default-value-for-angular-chain-dropdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!