Angular4 Form Builder动态

时间:2017-08-20 20:24:13

标签: angular

我正在使用Rails应用程序上的Angular(4),并尝试完成我的CRUD功能。我一直坚持如何处理“编辑”问题。就前端而言。

我在点击按钮时手动PUT ting测试了逻辑,但我很难让表格预先填充。

建议的流程

  • 用户点击执行Clients功能的getClients()
  • Clients页面的每个客户都有一个可点击的ID,可以转到clients/:id页面。
  • clients/:id执行传递getClientById()
  • params['id']函数
  • 表格预填充了信息
  • 提交editClientById

我的组件

@Component({
  selector: 'app-client-index',
  templateUrl: './client-index.component.html',
  styleUrls: ['./client-index.component.sass']
})
export class ClientIndexComponent implements OnInit {
  constructor(private clientService: ClientService,
              private activatedRoute: ActivatedRoute,
              private fb: FormBuilder
  ) { }
  public indexForm: FormGroup;
  public submitted: boolean;
  public events: any[] = [];
  client = Client;

  ngOnInit() {
    this.activatedRoute.params.subscribe((params: Params) => {
      let id = params['id'];
      this.clientService.getClientById(params['id']);
      this.indexForm = new FormGroup({
        name: ['', <any>Validators.required],
        status: [''],
        logo: ['']
    });
    }
  }


  edit(model: Client,  isValid: boolean) {
    this.submitted = true;

    console.log(model, isValid);
  }



  // demo(){
  //   console.log('pressed');
  //   this.clientService.editClientById({
  //     'id': 4,
  //     'name': 'Demo User2222',
  //     'status': 'This',
  //     'logo': "Test"
  //   })
  // }

}

服务

  getClientById(id): Observable<Client> {
    return this.authToken.get('clients/' + id)
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }


  editClientById(client:any): Observable<Client> {
    return this.authToken.patch('clients/' + client.id, client)
      .map(res => res.json())
      .catch((error: any) => Observable.throw(error.json().error || 'Server error'));
  }

目前的ngOnInit功能是我尝试的基于我发现的几篇SO文章和苏格兰教程。到目前为止,我得到的最接近的是我的提交按钮patch到API,但它没有预先填充该字段。

我目前的设置,根本不起作用。 我想知道是不是因为我的getClientById在ngOnInit完成加载之前正在运行,或者它是否正在运行。

我认为我需要以某种方式绑定到模型,但不确定如何。

1 个答案:

答案 0 :(得分:0)

您需要订阅在服务上调用getClientById的结果,然后获取结果并使用patchValue将检索到的客户端对象的字段放入表单字段中。

首先构建表单,然后订阅服务调用的结果:

e.g。 (只是输入了这个,没有经过测试......)

this.indexForm = new FormGroup({
        name: ['', <any>Validators.required],
        status: [''],
        logo: ['']
);
this.clientService.getClientById(params['id']).subscribe(client => {
    this.indexForm.patchValue({
 name: client.name,
 status: client.status,
 logo: client.logo
});