0

I have a service class:

class UserFormService {
    createUserForm() {
        const userForm = new FormGroup({
            firstName: new FormControl(),
            lastName: new FormControl(),
            displayName: new FormControl()
        })

        userForm.controls.firstName.valueChanges.subscribe(firstName => {
            if(!userForm.value.displayName) {
                userForm.controls.displayName.setValue(`${firstName} additional text`)
            }
        })

        return userForm
    }
}

The createUserForm methos is called in the component class. Is it required to cancel 'valueChanges' in the above code

Kuba K
  • 1
  • 1
  • 1
    maybe you can store the subscription and unsubscribe it in the ngDestroy – Farrukh Faizy Jan 02 '23 at 14:07
  • Does this answer your question? [Angular 2 - Does subscribing to FormControl's valueChanges need an unsubscribe?](https://stackoverflow.com/questions/41364078/angular-2-does-subscribing-to-formcontrols-valuechanges-need-an-unsubscribe) – Red Jan 02 '23 at 15:27

1 Answers1

0

I can't understand when a memory leak can occur in this case

For example:

@Component({
  selector: 'app-user-test',
  standalone: true,
    imports: [CommonModule, ReactiveFormsModule],
  templateUrl: './user-test.component.html',
  styleUrls: ['./user-test.component.css']
})
export class UserTestComponent {

  constructor(private userFormService: UserFormService) { }

    form = this.userFormService.createUserForm()
}

If the 'form' object is deleted, the subscription will also be deleted

In below code (https://angular-training-guide.rangle.io/routing/routeparams), we should unsubscribe because injected route object have reference to component object.

export class LoanDetailsPage implements OnInit, OnDestroy {
  id: number;
  private sub: any;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       this.id = +params['id']; // (+) converts string 'id' to a number

       // In a real app: dispatch action to load the details here.
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
}
Kuba K
  • 1
  • 1