Home > Blockchain >  Passing api value to formcontrolname
Passing api value to formcontrolname

Time:09-29

I'd like to get certain values from the API and pass them to the formcontrolname. The value of the API doesn't show in the field.

This is how I'm passing the data in the template.

<div *ngFor="let item of events">
    <div *ngFor="let x of item">
        <form action="" [formGroup]="SignupForm" (ngSubmit)="cancelBooking()">
            <div class="pageTitle SystemPageTitle text-center mt-5 schedule_heading">
               Slot : {{x.event_id}}
            </div>
            <div class="container mb-5 mt-3">
                <div class="card">
                    <div>
                        <input type="text" formControlName="person_id" value="{{x.person_id}}"><br>
                        <input type="text" formControlName="event_id" value="{{x.event_id}}">

                    </div>
                    <div class="" data-editablearea="0" data-areaheight="auto">
                        <p align="center"><button (click)="cancelBooking()" class="button buttonCancel">Delete</button>
                        </p>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>

Edit: I've added the setValue() function so that I pass the API data from the backend. My .ts file is as follows.

export class BookedEventComponent implements OnInit {
  events: any;
  SignupForm: any;
  x: any;

  constructor(
    private authService: AuthService,
    private router: Router,
    public formBuilder: FormBuilder,
  ) { }

  ngOnInit(): void {
    this.cancelForm();

    this.authService.getEvents().subscribe(response => {
      this.events = response;
      console.log(response);
    })
  }

  private cancelForm() {
    this.SignupForm = this.formBuilder.group({
      person_id: new FormControl(null),
      event_id: new FormControl(null),
    });
  }

  setValue() {
    this.SignupForm.setValue({
      person_id: this.x.person_id,
      event_id: this.x.event_id
    });
  }

  cancelBooking() {
    console.log(this.SignupForm.value);
    if (confirm("Are you sure you want to delete delete")) {
      this.authService.cancelSlot(this.SignupForm.value).subscribe(response => {
        window.location.reload();
        setTimeout(() => {
          this.router.navigate(['/schedule']);
        }, 1000);
      })
    }
  }
  
}

CodePudding user response:

You should set the value by setValue()

export class SimpleFormGroup {
      
  // data you get from API
  x;

  form = new FormGroup({
    person_id: new FormControl(null),
    event_id: new FormControl(null),
  });

  // Call this when you get data from API
  setValue() {
    this.form.setValue({
       person_id: x.person_id, 
       event_id: x.event_id
    });
  }
}

You also find out more at https://angular.io/api/forms/FormControlName

  • Related