Aymen Kanzari
Aymen Kanzari

Reputation: 2023

initialize a form with condition

I want to use a form depending on the results returned by a service, in my example if the conventions list is not null it calls the method initFormWithRequiredConvention, but the problem is that the list of conventions in the controller is undefined and in the HTML, the list of the convention is displayed

public conventions: Convention[];

constructor(private fb: FormBuilder, private conventionService: ConventionService) {
    if(this.conventions)
       this.initFormWithRequiredConvention();
    else
       this.initFormWithoutRequiredConvention();
}

public ngOnInit(): void {
    this.conventionService.getAll().subscribe((datas: any) => {
        this.conventions = datas.content;
    });
}

private initFormWithRequiredConvention(): void {
    const fb = this.fb;
    this.networkForm = this.fb.group({
        abstractName: fb.control(null, Validators.required),
        conventionsId: this.fb.array([
            this.fb.control(null, Validators.compose([Validators.required]))
        ])
    });
}

private initFormWithoutRequiredConvention(): void {
    const fb = this.fb;
    this.networkForm = this.fb.group({
        abstractName: fb.control(null, Validators.required),
        completeName: fb.control(null, Validators.required),
        countryId: fb.control(null, Validators.required),
        conventionsId: this.fb.array([
            this.fb.control(null)
        ])
    });
}

Upvotes: 0

Views: 591

Answers (1)

Vikas
Vikas

Reputation: 12036

You need to know the basic difference between constructor and ngOnInit.

A Constructor is a special type of method of a class and it will be automatically invoked when an instance of the class is created.

ngOnInit is a lifecycle hook offered by Angular that Angular calls shortly after creating the component.

The order of execution is Constructor-> ngOnInit

  1. The if-else block inside the constructor is redundant if(this.conventions) will never evaluate to true.
  2. you are invoking your getAll() method in ngOnInit subscribing it extracting the response and that's it what are you doing with it?? If you assumed constructor would be invoked again you are wrong.

use the constructor to invoke your default case.

constructor(private fb: FormBuilder, private conventionService:ConventionService){
this.initFormWithoutRequiredConvention();
}

Move your logic inside subscribe once it gets the result, appropriate method will be executed

`public ngOnInit(): void {
            this.conventionService.getAll().subscribe((datas: any) => {
                this.conventions = datas.content;

              if(this.conventions)
                  this.initFormWithRequiredConvention();
              else
                   this.initFormWithoutRequiredConvention();
            });
        }`

Upvotes: 1

Related Questions