簡體   English   中英

使用 angular 中的 patchValue 將值修補到復選框

[英]Patch values to checkbox using patchValue in angular

我正在嘗試重新使用我的create-form來編輯表單的值。 我的復選框在創建表單時按要求工作。 當我單擊編輯表單時,這些值不會修補到我的復選框。 以下是我嘗試過的代碼:

<div class="form-row">
  <div class="form-group col-sm-6">
    <label>Authorized To</label>
    <br>
    <label *ngFor="let choice of authorized; let i=index">
      <input type="checkbox" [value]="choice" (change)="onCheckChange($event)" [checked]="checkedVal"
          formArrayName="authorized" type="checkbox[class.invalid]="! formGrowLicense.controls['authorized'].valid && formGrowLicense.controls['authorized'].touched ">
                            {{choice}}
     </label>
    <div *ngIf="!formGrowLicense.controls['authorized'].valid && (formGrowLicense.controls['authorized'].touched || isSubmitted)">
      <div class="invalid-feedback" style="display: block;">Please enter authorized to</div>
    </div>

  </div>
</div>

ts

authorized: any = ['CULTIVATE', 'HARVEST', 'PROCESS']; //displaying list of checkbox
constructor() {
  this.formGrowLicense = this.formBuilder.group({
      businessName: ['', Validators.required], 
      authorized: new FormArray([], [Validators.required])
       });
   } 
 getGrowLicense(id) {
    this.httpService.getGrowLicenseById(id).subscribe(
      response => {
        this.patchGrowLicense(response);
        this.checkedVal = response.authorisedTo; // tried storing response in this variable  ['CULTIVATE','HARVEST']
      },

      (err: any) => console.log(err)
    );
  }
patch(licenseObj){
    this.formGrowLicense.patchValue({
      businessName:licenseObj.companyName,
      authorized: licenseObj.authorisedTo, // here i'm getting response ['CULTIVATE','HARVEST']. Need to patch these two values as checked in checkbox
      });
    }

 onCheckChange(event) {
    this.formArray = this.formGrowLicense.get(
      'authorized'
    ) as FormArray;

    /* Selected */
    if (event.target.checked) {
      console.log(event.target.value);
      // Add a new control in the arrayForm
      this.formArray.push(new FormControl(event.target.value));
    } else {
      /* unselected */
      // find the unselected element
      let i = 0;

      this.formArray.controls.forEach((ctrl: FormControl) => {
        if (ctrl.value == event.target.value) {
          // Remove the unselected element from the arrayForm
          this.formArray.removeAt(i);
          return;
        }

        i++;
      });
    }
  }

您有一個 FormControls 的 FormArray,它接受值 true/false 和接收的值以及固定數組中的字符串數組,因此首先您需要將接收到的數組轉換為 true/false 數組

第一種方法

首先,我們將創建一個帶有 formArray 的表單。 與往常一樣,我們可以管理一個表單數組,我們需要創建一個 getter 來返回我們的 formArray

  //our getter formArray
  get authorizedArray()
  {
    return this.formGrowLicense.get('authorized') as FormArray
  }

  ngOnInit()
  { //we create the formArray
    this.formGrowLicense=new FormGroup({
      businessName:new FormControl(),
      authorized:new FormArray(this.authorized.map(x=>new FormControl(false)))
    })
  }

看到創建 formArray 的方法是使用new FormArray(..here and array of formControls..) 創建formControls的formArray的方法是將數組“this.autorized”的每個元素“映射”到FormControl。

為了管理一系列輸入,我們使用 this.html

<form [formGroup]="formGrowLicense">
    <input formControlName="businessName">
    <!--we use formArrayName in a div-->
    <div formArrayName="authorized">
        <!--we iterate over autorizedArray.controls
           remember our getter of the formArray? -->
        <div *ngFor="let control of authorizedArray.controls;let i=index">
            <!--we use [formControlName]=i -->
            <label><input type="checkbox"  [formControlName]="i">{{authorized[i]}}</label>
        </div>
    </div>
</form>

與往常一樣,我們在.html 中使用(僅用於檢查)檢查是否一切正常

<pre>
  {{formGrowLicense?.value|json}}
</pre>

看看我們如何遍歷 formArrayControls,並使用索引,在 label 中顯示授權[i]

好吧,我們還知道如何控制表單數組,所以下一個問題:我們如何為 formArray 提供值?

請記住,我們收到了一些喜歡,例如

{
  businessName:'my business name'
  authorized:['CULTIVATE', 'PROCESS']
}

當我們收到數據中的值時,我們可以使用一些類似

   this.formGroupLicense.patchValue(
    {
     businessName:data.businessName,
     authorized:this.authorized.map(x=>data.authorized.indexOf(x)>=0)
    }

了解如何在 3 個元素的數組中使用 0、1、2 或 3 個元素轉換“data.authorize”和數組,該數組取值為 true 或 false

好吧,我們需要做的最后一項工作是,在提交時,使用 formArray 的值(例如 [true,false,false] 來獲取字符串數組

submit(form)
{
   if (form.valid)
   {
        const data={
           businessName:form.value.businessName
           authorize:form.value.authorized.map(
              (x,index)=>x?this.authorized[index]:null)
              .filter(x=>x)
        }
        console.log(data) //<--here we has the data we send to the service
   }
}

是的,我們 map [true,false,false]['CULTIVATE',null,null]並過濾並且只想要不是 null ['CULTIVATE']元素

好吧,使用 pathValue 是可以的,但是為什么我們不創建一個 function 來返回一個帶有我們想要的數據的 formGroup

createFormGroup(data:any=null)
{
    data=data||{businessName:null,authorize:[]}
    return new FormGroup({
      businessName:new FormControl(data.businessName),
      authorized:new FormArray(this.authorized
        .map(x=>new FormControl(data.authorized.indexOf(x)>=0)))
    })
}

所以,當我們收到數據時,我們唯一需要的就是使用

  this.formGroupLicense=this.createFormGroup(data)

第二種方法

我們有一個像

    this.formGrowLicense=new FormGroup({
      businessName:new FormControl(),
      authorized:new FormControl()
    })

是的。 授權是一個存儲數組的 FormControl。 如果看到材質多勾選就是這種方法。 為此,您可以使用自定義 formControl 檢查此SO 讓我解釋一下(我不想要 customFormControl)

我們有一個輔助數組,其中包含兩個屬性“名稱”和“值”,我們希望得到一些類似的屬性,例如

authorizedAux: any = [{name:'CULTIVATE',value:true}, 
                      {name:'HARVEST',value:false},
                      {name:'PROCESS',value:true}]

所以我們添加了一個 function

  setAutorized(data: string[]) {
    this.authorizedAux = this.authorized.map(x => ({
      name: x,
      value: data.indexOf(x) >= 0
    }));
  }

和另一個 function 解析

  parse() {
    const result=this.authorized
      .map((x, index) => (this.authorizedAux[index].value ? x : null))
      .filter(x => x);
    return result.length>0?result:null
  }

然后我們可以有一個 html 使用 ngModel、ngModelChange 和 ngModelOptions 來更改 FormControl 的值

<form [formGroup]="form">
    <input formControlName="businessName">
        <div *ngFor="let control of authorizedAux">
            <label>
        <input type="checkbox"  
            [ngModel]="control.value"
            (ngModelChange)="control.value=$event;form.get('authorized').setValue(parse())"
            [ngModelOptions]="{standalone:true}"
      >{{control.name}}</label>
        </div>
</form>

請記住,當收到數據時,我們需要調用 function setAutorized

查看stackblitz中的兩種方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM