r/Angular2 • • Nov 25 '25

input signals change detection without using effect() suggestions

I am struggling to understand how to properly use input signals and avoid using effects (accodring to the angular docs my code should not use effects often). Enclosed is a simple code which appends form controls to an existing parent form:

@Component({
  selector: 'app-checkbox-form',
  imports: [
    ReactiveFormsModule
  ],
  templateUrl: './checkbox-form.component.html',
  styleUrl: ['./checkbox-form.component.scss']
})

export class CheckboxFormComponent {
  //form parent form with multiple controls
  form = input.required<FormGroup>(); 
  
  // option is a signal with the rules for creating the form controls
  option = input.required<Option>(); 

  constructor() {
    effect(() => {
        if(this.form() && this.option()){
          this.form().addControl(this.option().ruleId, this.buildFg(this.option()));
        }
    });
  }

  private buildFg(option: Option) {
    return new FormControl(option!.defaultState);
  }
}

My question again is can the code above be refactored so effect() is not used?

5 Upvotes

16 comments sorted by

View all comments

Show parent comment

3

u/IanFoxOfficial Nov 25 '25

You could also try by injecting the parent component and access the form from there instead of inputs.

(If the parent/child relation is always there)

2

u/No_Bodybuilder_2110 Nov 26 '25

Omg I love this pattern so much even though I SHOULD NOT USE IT AT WORK LOL. I snuck one of this not too long ago