I have built a custom formly control, how do I subscribe to it's custom event in the onInit lifecycle hook?

1k Views Asked by At

my custom formly control has an "optionChanged" event, which looks like this:

@Component({
  selector: 'app-formly-company-search',
  templateUrl: './formly-company-search.component.html',
  styleUrls: ['./formly-company-search.component.scss']
})
export class FormlyCompanySearchComponent extends FieldType implements OnInit {
  label: string;
  @Output() optionChanged = new EventEmitter<string>();
  constructor() {
    super();
  }

  ngOnInit() {
    this.label = this.field.templateOptions.label;

    if (this.field.templateOptions.required) {
      this.label += " *";
    }
  }

  onOptionChanged(option) {
    //console.log("new option: ", option);
    this.field.templateOptions.optionChanged(option);
  }
}

By calling optionChanged in the templateOptions as above I can implement an event handler when I define the control in my FormlyFieldsConfig like this:

this.fields = [
  {
    fieldGroup: [
      {
        key: 'EmployerKey',
        type: 'company-search',
        templateOptions: {
          required: true,
          label: 'Employer Search',
          optionChanged: ($event) => {
            this.setPaySchedulesForEmployer2($event);
            this.setTaxYearsForEmployer($event);
          }
        }
      },

Which works well. But I also would like to subscribe to this event (kind of as I would do for the valueChanges event) in an onInit lifecycle hook for another formly control like this:

      {
        key: 'PayFrequency',
        type: 'select',
        templateOptions: {
          label: 'Pay Frequency',
          valueProp: 'Key',
          labelProp: 'Text'
        },
        hooks: {
          onInit: (field: FormlyFieldConfig) => {
            let employerControl = this.form.get("EmployerKey");
            this.subs.add(employerControl.optionChanged.subscribe(result => {
              this.onEmployerChanged(field);
            }));
          }
        }
      },

But of course the "employerControl" FormControl doesn't have that event "optionChanged" so I'm not sure how I could go about this? Thanks.

0

There are 0 best solutions below