Angular 4 Dynamic Forms: Dependent Dropdown

拜拜、爱过 提交于 2019-12-03 17:30:29

I would add one option called showWhen to base model:

base.model.ts

export class BaseModel<T> {
  value: T;
  key: string;
  label: string;
  required: boolean;
  order: number;
  controlType: string;
  showWhen: ControlCondition; <===================== new option

  constructor(options: {
    value?: T,
    key?: string,
    label?: string,
    required?: boolean,
    order?: number,
    controlType?: string,
    showWhen?: ControlCondition
  } = {}) {
    this.value = options.value;
    this.key = options.key || '';
    this.label = options.label || '';
    this.required = !!options.required;
    this.showWhen = options.showWhen;
    this.order = options.order === undefined ? 1 : options.order;
    this.controlType = options.controlType || '';
  }
}

export class ControlCondition {
  key: string;
  value: string;
}

As you can see it takes key and value. Depending on these values we can decide whether to show control or not.

Now you can describe condition for showing your controls like:

new DropdownInput({
  key: 'dropdown',
  label: 'Dropdown Testing',
  options: [
    { key: 'example1', value: 'Example 1' },
    { key: 'example2', value: 'Example 2' }
  ],
  order: 1
}),

new CheckboxInput({
  key: 'checkbox1',
  label: 'checkbox1 - example1',
  showWhen: {
    key: 'dropdown',   // if control with key `dropdown` has value `example 1` then show
    value: 'example1',
  },
  order: 2
}),

Now go to the component that is called DynamicFormQuestionComponent in angular tutorial. In my example I called it DynamicFormComponent. Here we need to add logic for showing/hidding control:

dynamic-form.component.ts

export class DynamicFormComponent implements OnInit, OnDestroy {
  @Input() input: BaseModel<any>;
  @Input() form: FormGroup;

  control: FormControl;

  hidden: boolean;

  subscription: Subscription;

  ngOnInit() {
    this.control = this.form.get(this.input.key) as FormControl;
    this.setUpConditions();
  }

  setUpConditions() {
    if (!this.input.showWhen) {
      return;
    }

    let relatedControl = this.form.get(this.input.showWhen.key);
    if (!relatedControl) {
      return;
    }

    this.updateHidden();
    this.subscription = relatedControl.valueChanges.subscribe(x => this.updateHidden());
  }

  updateHidden(): void {
    let relatedControl = this.form.get(this.input.showWhen.key);
    this.hidden = relatedControl.value !== this.input.showWhen.value;

    this.hidden ? this.control.disable() : this.control.enable();
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

and last thing you need to do is to add *ngIf="!hidden" in template

Ng-run Example

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