Angular 2 Dynamic Forms: How to create dependent d

2019-04-16 04:49发布

I am creating dynamic form by referring to Angular 2 Dynamic Forms

Everything works good. but the problem I am facing is creating dependent drop-down. eg: I want to create form where user can select there address using Country, City, State drop-down.

new DropdownField({
  key: 'country',
  label: 'Country',
  options: [
    {key: 'usa',  value: 'USA'},
    {key: 'uk',  value: 'UK'}
  ],
  order: 4
}),

new DropdownField({
  key: 'state',
  label: 'State',
  options: [
    {key: 'taxas',  value: 'taxas'},
    {key: 'detroit',  value: 'detroit'}
  ],
  order: 5
}),

new DropdownField({
  key: 'city',
  label: 'City',
  options: [
    {key: 'houston',  value: 'Houston'},
    {key: 'austin',  value: 'Austin'}
  ],
  order: 5
})

Edit: Following is the template.

<div class="form-group" [formGroup]="form">
  <label [attr.for]="field.key" class="control-label">{{field.label}}</label>
  <div [ngSwitch]="field.controlType">
    <input *ngSwitchCase="'textbox'"
      formControlName="{{field.key}}"
      [id]="field.key"
      [type]="field.type"
      class="form-control"
      [placeholder]="field.placeholder"
      [readonly]="field.readonly"
    >
    <select [id]="field.key" *ngSwitchCase="'dropdown'" formControlName="{{field.key}}" class="form-control">
      <option style="display:none" value="">Choose an option</option>
      <option *ngFor="let opt of field.options" [value]="opt.key">{{opt.value}}</option>
    </select>
  </div>
  <div style="color: red;" *ngIf="!isValid">({{field.label}} is required)</div>
</div>

What I want is when user select Country, list of State should get populated and when user select State, list of City should get populated but all using Dynamic Forms.

1条回答
beautiful°
2楼-- · 2019-04-16 05:19

Here's a Plunkr which demonstrates dependent drop-downs: https://plnkr.co/edit/b5FKSp06XMfQul5pYQti?p=preview

It has a first drop-down list to select a product type (small or large) which updates a second drop-down list showing only the small or the large products. You could easily translate this example to dependent drop-downs for country/state/city.

The Plunkr shows two techniques to generate the values for the dependent drop-down:

  • Recalculating the values on every change event emitted by the first drop-down.
  • Applying a custom pipe to the values of the dependent drop-down so that they are automatically bound to & filtered by the value of the first drop-down.
查看更多
登录 后发表回答