无法在Angular反应性表单中的表单加载上设置默认值

时间:2019-07-29 20:37:48

标签: angular angular7 angular-reactive-forms

基本上,我需要通过传递id来执行http请求。得到响应后,需要将值分配给表单字段。

我尝试使用setValue和patchValue。但是没用

spService

itemData = new ItemData()

    getItembyID(itemID) {
          return this.http.get<Object>(this.baseUrl +"items("+itemID+")")
          .pipe(map ((response : Response) => {
            const data = response['d']
            return data
          })
          ).subscribe((data : Response) => {
              this.setItemData(data)
          })
        }

    setItemData(data) {
        this.itemData.requestno  = data.Request_x0020_Number
        this.itemData.requestid  = data.Request_x0020_ID

edit-form.component.ts

constructor(private spService : SharepointService,
                  private formBuilder : FormBuilder)

 ngOnInit() {
   this.route.params.subscribe((param : Params)=> {
            const id = param['ID']
            this.spService.getItemByID(ID)
       })

    this.itemData = this.sharepointService.itemData 
    // In console, I can see the details of the itemData but not able to set to the formcontrols.

    this.editForm = this.formBuilder.group({
       RequestNo : [''],
       RequestId : ['']
    })

    this.editForm.patchValue({
      RequestNo : this.itemData.requestno,
      RequestId : this.itemData.requestid

    })
    }   // End of OnInit

edit-form.component.html


<form [formGroup]= "editForm">
  <label> DefaultRequestNo </label>
  <input type="text" formControlName="RequestNo">

   <label> DefaultRequestID </label>
    <input type="text" formControlName="RequestId">

</form>

3 个答案:

答案 0 :(得分:1)

这里的问题是服务中的itemData不能同步使用,但是您正在访问它,就像访问它一样。您应该在服务中设置组件可以订阅的主题:

修改后的SP服务:

  itemData = new ItemData();
  private itemDataSource = new ReplaySubject<ItemData>(1);
  itemData$ = this.itemDataSource.asObservable();

  getItembyID(itemID) {
    return this.http.get<Object>(this.baseUrl +"items("+itemID+")")
      .pipe(map ((response : Response) => {
        const data = response['d']
        return data
      })
      ).subscribe((data : Response) => {
          this.setItemData(data)
      })
  }

  setItemData(data) {
    this.itemData.requestno  = data.Request_x0020_Number;
    this.itemData.requestid  = data.Request_x0020_ID;
    this.itemDataSource.next(this.itemData);
  }

然后您可以订阅组件:

// just do this once
this.editForm = this.formBuilder.group({
   RequestNo : [''],
   RequestId : ['']
})

this.sharepointService.itemData$.subscribe(itemData => {
  this.itemData = itemData;
  this.editForm.setVale({
    RequestNo : this.itemData.requestno,
    RequestId : this.itemData.requestid
  });
});

您的日志“撒谎”给您的原因;在您的服务中,您可以设置一个初始对象值,然后仅对该对象进行突变。当您在控制台中记录对象时,它不会显示“时间点”值,而是显示对该对象的引用以及该引用的值,因此即使在以下情况下数据实际上不可用您尝试设置表单值,但最终设置时它仍会出现在日志中。

这是为什么应该避免在Javascript中普遍进行对象突变,而是在每次更改以下内容时实例化一个新对象的众多原因之一。

  setItemData(data) {
    this.itemData = Object.assign({}, this.itemData, {
      requestno: data.Request_x0020_Number,
      requestid: data.Request_x0020_ID
    });

    this.itemDataSource.next(this.itemData);
  }

此方法将确保您不会突变新对象,而是每次都创建一个新对象。这种特定的方法可能不适合您的用例,但是原理是相同的,请勿更改。

答案 1 :(得分:1)

要在编辑点击时设置默认值,可以使用 @ rxweb / reactive-form-validators 中的FormBuilderConfiguration,在其中可以设置值来自defaultValue属性中的edit api调用,如下所示:

 setItemData()
    {
           let user = new User();
         var formBuilderConfig = new FormBuilderConfiguration();
        formBuilderConfig.propsConfig = {'RequestNo':{defaultValue:"abc1"},"RequestId":{defaultValue:1}}
         this.editForm = <RxFormGroup>this.formBuilder.formGroup(user,formBuilderConfig);
    }

您需要在应用程序组件中导入RxReactiveFormsModule

这是完整的组件代码

import { Component, OnInit } from '@angular/core';
import { FormGroup,FormArray } from "@angular/forms"
import { RxFormBuilder,RxFormGroup,FormBuilderConfiguration } from '@rxweb/reactive-form-validators';

import { User, } from './user.model';

@Component({
    selector: 'app-user',
    templateUrl: './patch-complete.component.html'
})
export class UserComponent implements OnInit {
    editForm: RxFormGroup

    constructor(
        private formBuilder: RxFormBuilder    ) { }

    ngOnInit() {
        let user = new User();
        this.editForm = <RxFormGroup>this.formBuilder.formGroup(user); 
         // this.itemData = this.sharepointService.itemData 
    // In console, I can see the details of the itemData but not able to set to the formcontrols.
    }
 
    setItemData()
    {
           let user = new User();
         var formBuilderConfig = new FormBuilderConfiguration();
        formBuilderConfig.propsConfig = {'RequestNo':{defaultValue:"abc1"},"RequestId":{defaultValue:1}}
         this.editForm = <RxFormGroup>this.formBuilder.formGroup(user,formBuilderConfig);
    }
}
<div>

   <form [formGroup]= "editForm">
  <label> DefaultRequestNo </label>
  <input type="text" formControlName="RequestNo">
<br/>
   <label> DefaultRequestID </label>
    <input type="text" formControlName="RequestId">
    <br/>
<button (click)="setItemData()">SetItemData</button>
</form>
</div>

这里是Working Example

答案 2 :(得分:0)

似乎您正在尝试手动设置默认值,而不是让FormBuilder管理它们。您应该尝试将上面的代码修改为:

input[type=checkbox]:checked ~ .first-class ~ .second-class ~ .third-class {
    display: flex;
}

应该可以。