将 api 值传递给 formcontrolname

Passing api value to formcontrolname

我想从 API 中获取某些值并将它们传递给 formcontrolname。 API 的值未显示在字段中。

这就是我在模板中传递数据的方式。

<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>

编辑: 我添加了 setValue() 函数,以便从后端传递 API 数据。 我的.ts文件如下

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);
      })
    }
  }
  
}

您应该通过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
    });
  }
}

您还可以在 https://angular.io/api/forms/FormControlName

中找到更多信息