【问题标题】:Fill reactive form initial data from service从服务中填充响应式表单初始数据
【发布时间】:2019-05-18 07:50:38
【问题描述】:

使用 Angular 7 和反应式表单我在组件上有以下内容:

ngOnInit() {

  this.postForm = this.formBuilder.group({ 
    categoryId: [''],  
    title: [''],
    content: ['']
  });

}

getPost(postId: number) : Observable<Post> {

  return this.postService.getByPostId(postId);

}

其中PostService的GetByPostId方法如下:

public getByPostId(postId: number): Observable<Post> {

  return this.httpClient.get<Post>(`posts/${postId}`);

}

postService返回一个Post,接口是:

interface Post {
  id: number;
  categoryId: number;
  title: string;
  content: string;
}

从 getPost 返回的内容中填充表单数据的正确方法是什么?

【问题讨论】:

    标签: angular angular7 angular-reactive-forms


    【解决方案1】:

    最好的方法是使用patchValue 方法:

    updateProfile() {
     this.profileForm.patchValue({
        firstName: 'Nancy',
        address: {
          street: '123 Drew Street'
        }
      });
    }
    

    更多信息:here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 2019-10-24
      • 2017-05-15
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多