How to show assign value in form group get from api object

Viewed 29

I am working on edit functionality in angular 14. My requirments are bit diff thats why i am not using set value to assign value in form . I have get the value from api in the form of model

export class EditCandidateComponent implements OnInit {
  candidateData: any;
  response: any;
  editCandidateSubmitted = false;
  data = new Candidate();

  constructor(private route: ActivatedRoute, private candidateService: CandidateService) { }

  ngOnInit(): void {
    this.getCandidate(this.route.snapshot.params.id);
  }

  getCandidate(id:any)
  {
    this.candidateService.getCandidate(id).subscribe(
      (resp: Candidate) => { 
        this.setformValue(resp);
      },
      (err: any) => {
        console.log(err+'new');
      }
    );
  }
  setformValue(updateValue) {
    this.data = updateValue;
    console.log(this.data);
  }

  addCandidate = new FormGroup({
    first_name: new FormControl(this.data.first_name, [
      Validators.required,
      Validators.pattern(AppConstants.OnlyAlphabetic),
    ]),
    last_name: new FormControl(this.data.last_name, [
      Validators.required,
      Validators.pattern(AppConstants.OnlyAlphabetic),
    ]),
  });

  get candidateFormControl() {
    return this.addCandidate.controls;
  }
  
  onSubmit() {

  }

Here is my http call with model in return

return this.http.get<any>(slug, {observe: "response"}).pipe(map(
  (res) => { 
    return new Candidate(
            res.body.data['first_name'],
            res.body.data['last_name'],
            ); 
  })
);

I have tried set value but I am not using it because I have diff requirments. I want to show th value in formgroup. When i tried to move formgroup in setformValue function it give my error so how i can do this.

Here is the model

export class Candidate {
    constructor(
        public first_name : string = '',
        public last_name : string = '',
    )  {}
}
1 Answers

You must first initialize your form. For that, add in your ngOnInit a function like that:

ngOnInit(): void {
    this.initForm();
    this.getCandidate(this.route.snapshot.params.id);
}

 // ...
 
private initForm(): void {
    this.form = new FormGroup({
        first_name: new FormControl(this.data.first_name, [
          Validators.required,
          Validators.pattern(AppConstants.OnlyAlphabetic),
        ]),
        last_name: new FormControl(this.data.last_name, [
          Validators.required,
          Validators.pattern(AppConstants.OnlyAlphabetic),
        ]),
      });
}

Don't forget to declare a variable form: FormGroup; in your class variable member declarations. Then you just need to update a little bit your getCandidate function with the following changes:

getCandidate(id:any)
  {
    this.candidateService.getCandidate(id).subscribe(
      (resp: Candidate) => { 
        this.form.get('first_name').setValue(resp.first_name);
        this.form.get('last_name').setValue(resp.last_name);
      },
      (err: any) => {
        console.log(err+'new');
      }
    );
  }

You didn't post your Candidate class, but I presume it contains public attributes first_name and last_name or getter. Please adapt the names if they are not matching your Candidate class member variables.

UPDATE Please try with this following logic (component/template)

Your component:

export class EditCandidateComponent implements OnInit {
    form: FormGroup;

    constructor(private route: ActivatedRoute, private candidateService: CandidateService) { }

    ngOnInit(): void {
        this.initForm();
        this.getCandidate(this.route.snapshot.params.id);
    }

    getCandidate(id: any) {
        this.candidateService.getCandidate(id).subscribe(
          (resp: Candidate) => { 
            this.setformValue(resp);
          },
          (err: any) => {
            console.log(err+'new');
          }
        );
    }

    setformValue(response: Candidate) {
        this.form.get('first_name').setValue(response.first_name);  
        this.form.get('last_name').setValue(response.last_name);  
    }

    private initForm(): void {
        this.form = new FormGroup({
            first_name: new FormControl('', [
              Validators.required,
              Validators.pattern(AppConstants.OnlyAlphabetic),
            ]),
            last_name: new FormControl('', [
              Validators.required,
              Validators.pattern(AppConstants.OnlyAlphabetic),
            ])
        });
    }
  
  // ... rest of your component ...
}

Your template HTML:

<div [formGroup]="form">
    <input formControlName="first_name">
    <input formControlName="last_name">
</div>
Related