programing

폼 제어를 비활성화하되 값은 유지하는 방법

lovejava 2023. 9. 11. 21:19

폼 제어를 비활성화하되 값은 유지하는 방법

저는 반응형이 있습니다.편집 시 컨트롤을 사용하지 않도록 설정합니다.

다음이 작동합니다.

   this.myForm.controls['analysis_horizon'].disable();

그러나 key analysis_horizon이 더 이상 myForm.value 해시에 없습니다.

반응형 폼은 있지만 폼 값은 해시 값으로 유지하는 필드를 비활성화하려면 어떻게 해야 합니까?

[disabled]=을(를) 시도했지만 다음을 확인할 수 있습니다.

It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
      when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
      you. We recommend using this approach to avoid 'changed after checked' errors.

      Example: 
      form = new FormGroup({
        first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
        last: new FormControl('Drew', Validators.required)
      });

편집할 때 데이터베이스의 데이터를 양식 컨트롤에 로드하지만 변경할 수 없도록 하려면 하나의 필드가 필요합니다.

속성 대신 getRawValue()를 사용할 수 있습니다.문서에 의하면 다음과 같습니다.

비활성화된 컨트롤을 포함하여 FormGroup의 집계 값입니다.

비활성화 상태에 관계없이 모든 값을 포함하려면 이 방법을 사용합니다.그렇지 않으면 속성이 그룹의 값을 얻는 가장 좋은 방법입니다.

this.myForm.getRawValue()

제 솔루션은 [attr.disabled]를 사용하는 것입니다.

<select formControlName="foo"
  [attr.disabled]="disabled == true ? true : null"> 
</select>

구성 요소에 비활성화된 속성이 있다고 가정합니다.입력을 활성화하려면 null을 false가 아닌 retun해야 합니다.

폼에서 값을 가져오는 일반적인 방법을 변경하는 getRawValue를 사용하지 않으려면 다음 옵션이 있습니다.제가 더 좋아하는 이유는 https://stackoverflow.com/a/7730719/1678151 입니다.

내 솔루션은 양식 컨트롤을 채우는 방법도 보여줍니다.

component.ts

fillForm(data: any){
 if (data != null && data.firstName){
   this.form.patchValue({
     firstName: data.firstName
   })    
   this.firstNameIsReadOnly = true;
 } 

template.semplate

<input formControlName="firstName" [readonly]='firstNameIsReadOnly'>

style.scss

input[readonly] {
 color: rgba(0,0,0,.38);
}

추가 시도onlySelf: true내부 메서드 사용 안 함:

this.myForm.controls['analysis_horizon'].disable({onlySelf: true});

반응형 양식으로 각도 재료 날짜 선택기를 구현하려고 하다가 이 문제가 발생했습니다. 입력을 비활성화하여 선택기만 날짜를 설정할 수 있기를 원했지만 각도가 사용자에게 소리칩니다.disabled템플릿에서 속성을 지정한 다음 구성 요소 폼 그룹 코드에서 값을 제거합니다.

제가 생각해낸 해결책은 CSS를 사용하여 입력과의 상호작용을 방지하는 것입니다.

.disable-pointer-events {
   pointer-events: none;
}
<input
  class="disable-pointer-events"
  formControlName="yourControlName"
/>

컨트롤(Control) 형식의 가치를 잃지 않고 우아하게 처리하기 위해 사용합니다.

[readonly]= condition ? true : false

이 문제의 해결책을 찾고 있던 중에 onSubmit 기능에서 속성을 다시 변경하는 또 다른 우아한 APROUCH를 발견했습니다.

onSubmit() {
console.log('Before', this.myForm.value);

 this.myForm.controls['analysis_horizon'].enable();  // if edit

console.log('After', this.myForm.value);

}

안부 전해요

저는 보통 다음과 같은 접근법을 사용합니다. (맞춤형 제어에는 신경쓰지 않음) - 재료 제어도 가능합니다, fb는 a입니다.FormBuilder DI):

사용하는 코드:

          this.addressTypeForm = this.fb.group({
            id: [null],
            ...
          });
          this.addressTypeForm.patchValue(this.selectedAddressType); //or patch only specific fields

selectedAddressType에는 일부 외부 소스에서 읽은 데이터가 들어 있으며 "읽기 전용"으로 간주됩니다.그런 다음 특정 데이터는 다음을 통해 형식으로 복사됩니다.patchValue를 들어 가 - 를 를 를 가 를 id 읽기 -식기용스다만신다만스i용et기d신t식am .

사용하는 마크업:

          <ng-container
            *ngIf="isNewAddressType; then addAddressTypeSelection; else editAddressTypeLabel"
          ></ng-container>
          <ng-template #addAddressTypeSelection>
            <bc-text
              [label]="'::AddressManagement:Id' | abpLocalization"
              [error]="abxForm.get('id').invalid && abxForm.get('id').touched"
              formControlName="id"
            ></bc-text>
          </ng-template>
          <ng-template #editAddressTypeLabel>
            <bc-text
              *ngIf="selectedAddressType"
              [label]="'::AddressManagement:Id' | abpLocalization"
              [disabled]="true"
              [value]="selectedAddressType.id"
            ></bc-text>
          </ng-template>

결국 양식에서 데이터를 저장하려는 경우(논리적인 경우) 특정 컨트롤을 사용하지 않도록 설정하지 않을 수 있습니다. 이 경우 해당 컨트롤의 값이 손실되기 때문입니다.를 들면,약,를 가지고 있다면id 다른 으로 동적으로 control터화는로화로을른):화는로(l화로터d른을ty ):

          this.addressTypeForm = this.fb.group({
            id: [{ value: 111, disabled: true }],
            ...
          })

여기에 자동으로 표시되지 않습니다.

            <bc-text
              [label]="'::AddressManagement:Id' | abpLocalization"
              [error]="abxForm.get('id').invalid && abxForm.get('id').touched"
              formControlName="id"
            ></bc-text>

하지만 그러한 양식을 저장하는 동안, 당신은 느슨해질 것입니다.idvalue

저는 보통 전체 양식을 비활성화하고 활성화합니다.그러나 결코 - 특정 양식 제어(의도적으로 가치를 "잃어버리고 싶지만" 그런 경우는 한 번도 없었습니다).

언급URL : https://stackoverflow.com/questions/42180696/how-to-disable-form-control-but-keep-value