首页 > 解决方案 > 如何在 Angular 组件中重新加载表单

问题描述

我有一个用于路由导航的组件,无需重新加载组件:

export class TableComponent extends SafeComponent implements OnInit {
  customersMe$: Observable<ICompanyCustomer>;
  customersMe: ICompanyCustomer;
  tables$: Observable<ITable[]>;
  headersLoaded$: Observable<boolean>;
  headerLoading = true;

  table: ITable;
  TableForm: FormGroup;
  constructor(
    private store: Store<State>,
    private router: Router,
    private route:ActivatedRoute,
    private changeDetectorRef: ChangeDetectorRef,
  ) {
    super();
  }

  ngOnInit(): void {
    this.tables$ = this.store.pipe(select(getTables));
    this.headersLoaded$ = this.store.pipe(select(getLoaded));

    combineLatest([this.tables$, this.headersLoaded$, this.route.params])
      .subscribe(([tables, loaded, params]) => {
        if (loaded) {
          this.headerLoading = false;
          const table = tables.find(x => x.id === Number(params['id']));
          if (table) {
            this.table = table;
          } else {
            // navigate 404
          }
          this.changeDetectorRef.detectChanges();
        }
      })


  /*  this.tableForm = new FormGroup({
   *    start: new FormControl(this.table.time_start),
   *    end: new FormControl(this.table.time_finish)
   *});*/

  }
}

正如您在这里注意到的那样,我订阅了路由并更新了路由路径中新 id 的数据。如何更新表单组中的数据?谢谢!

标签: angular

解决方案


如果您尝试使用值填充表单字段,您可以尝试: 对于填充所有字段:

this.form.setValue({name: 'Kakashi', address: { village: 'Konoha', country: 'Fire'}});

填充一些字段:

this.form.patchValue({name: 'Kakashi', address: { village: 'Konoha', country: 'Fire'}});

推荐阅读