Programing

반응 형 입력 필드 비활성화

lottogame 2020. 11. 23. 07:38
반응형

반응 형 입력 필드 비활성화


나는 이미 여기에서 다른 답변의 예를 따르려고 시도했지만 성공하지 못했습니다!

반응 형 (즉, 동적)을 만들었고 특정 시간에 일부 필드를 비활성화하고 싶습니다. 내 양식 코드 :

this.form = this._fb.group({
  name: ['', Validators.required],
  options: this._fb.array([])
});

const control = <FormArray>this.form.controls['options'];
control.push(this._fb.group({
  value: ['']
}));

내 HTML :

<div class='row' formArrayName="options">
  <div *ngFor="let opt of form.controls.options.controls; let i=index">
    <div [formGroupName]="i">
      <select formArrayName="value">
        <option></option>
        <option>{{ opt.controls.value }}</option>
      </select>
    </div>
  </div>
</div>

용이하게하기 위해 코드를 줄였습니다. 유형 선택 필드를 비활성화하고 싶습니다. 다음을 시도했습니다.

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

작동 안함! 누구에게 제안이 있습니까?


name: [{value: '', disabled: true}, Validators.required],
name: [{value: '', disabled: this.isDisabled}, Validators.required],

또는

this.form.controls['name'].disable();

주의

조건 변수를 사용하여 양식을 만들고 나중에 변경하려고하면 작동 하지 않습니다 . , 양식이 변경되지 않습니다 .

예를 들면

this.isDisabled = true;

this.cardForm = this.fb.group({
    'number': [{value: null, disabled: this.isDisabled},
});

그리고 변수를 변경하면

this.isDisabled = false;

양식은 변경되지 않습니다. 당신은 사용해야합니다

this.cardForm.get ( 'number'). disable ();

BTW.

값을 변경하려면 patchValue 메서드를 사용해야합니다.

this.cardForm.patchValue({
    'number': '1703'
});

반응 형 양식이있는 DOM에서 disable을 사용하는 것은 나쁜 습관입니다. 당신은 당신이 옵션을 설정할 수 있습니다 FormControl당신이에서 init을 때,

username: new FormControl(
  {
    value: this.modelUser.Email,
    disabled: true
  },
  [
    Validators.required,
    Validators.minLength(3),
    Validators.maxLength(99)
  ]
);

재산 value이 필요하지 않습니다

또는 다음을 사용하여 양식을 제어 get('control_name')하고 설정할 수 있습니다.disable

this.userForm.get('username').disable();

보다 일반적인 접근 방식이 있습니다.

// Variable/Flag declare
public formDisabled = false;

// Form init
this.form = new FormGroup({
  name: new FormControl({value: '', disabled: this.formDisabled}, 
    Validators.required),
 });

// Enable/disable form control
public toggleFormState() {
    this.formDisabled = !this.formDisabled;
    const state = this.formDisabled ? 'disable' : 'enable';

    Object.keys(this.form.controls).forEach((controlName) => {
        this.form.controls[controlName][state](); // disables/enables each form control based on 'this.formDisabled'
    });
}

이것은 나를 위해 일했습니다. this.form.get('first').disable({onlySelf: true});


사용하는 경우 disabled(정답에 제안처럼 폼 입력 요소 방법을 비활성화 입력에 그들도 비활성화되어 주목을 취할 것입니다에 대한 검증)!

(그리고 제출 버튼을 사용하는 경우 [disabled]="!form.valid"유효성 검사에서 필드가 제외됩니다)

enter image description here


필드 세트의 레이블로 입력 객체를 래핑하여 해결했습니다. 필드 세트에는 부울에 바인딩 된 disabled 속성이 있어야합니다.

 <fieldset [disabled]="isAnonymous">
    <label class="control-label" for="firstName">FirstName</label>
    <input class="form-control" id="firstName" type="text" formControlName="firstName" />
 </fieldset>

first(formcontrol) 을 비활성화 하려면 아래 문을 사용할 수 있습니다.

this.form.first.disable();


최고의 솔루션은 다음과 같습니다.

https://netbasal.com/disabling-form-controls-when-working-with-reactive-forms-in-angular-549dd7b42110

솔루션 개요 (링크가 끊어진 경우) :

(1) 지시문 작성

import { NgControl } from '@angular/forms';

@Directive({selector: '[disableControl]'})
export class DisableControlDirective {

  @Input() set disableControl( condition : boolean ) {
    const action = condition ? 'disable' : 'enable';
    this.ngControl.control[action]();
  }

  constructor( private ngControl : NgControl ) {}
}

(2) 그렇게 사용

<input [formControl]="formControl" [disableControl]="condition">

(3) Since disabled inputs do not show in form.value on submit you may need to use the following instead (if required):

onSubmit(form) {
  const formValue = form.getRawValue() // gets form.value including disabled controls
  console.log(formValue)
}

To make a field disable and enable of reactive form angular 2+

1.To disable

  • Add [attr.disabled]="true" to input.

<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">

To enable

export class InformationSectionComponent {
formname = this.formbuilder.group({
firstname: ['']
});
}

Enable whole form

this.formname.enable();

Enable particular field alone

this.formname.controls.firstname.enable();

same for disable, replace enable() with disable().

This Works fine. Comment for queries.


I had the same problem, but calling this.form.controls['name'].disable() did not fixed it because I was reloading my view (using router.navigate()).

In my case I had to reset my form before reloading:

this.form = undefined; this.router.navigate([path]);

참고URL : https://stackoverflow.com/questions/42840136/disable-input-fields-in-reactive-form

반응형