반응 형식의 입력 필드 사용 안 함
저는 이미 여기서 다른 답의 예를 따르려고 노력했지만 성공하지 못했습니다!
반응형 양식(즉, 동적)을 작성했으며 지정된 시간에 일부 필드를 사용하지 않도록 설정하려고 합니다.내 양식 코드:
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>
쉽게 하기 위해 코드를 줄였습니다.type select 필드를 비활성화합니다.저는 다음을 시도했습니다.
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();
그건 그렇고.
값을 변경하려면 patchValue 메서드를 사용해야 합니다.
this.cardForm.patchValue({
number: '1703'
});
입력 개체를 필드 집합의 레이블로 감아서 해결했습니다.필드 집합에는 비활성화된 속성이 부울에 바인딩되어 있어야 합니다.
<fieldset [disabled]="isAnonymous">
<label class="control-label" for="firstName">FirstName</label>
<input class="form-control" id="firstName" type="text" formControlName="firstName" />
</fieldset>
반응형이 있는 DOM에서 비활성화를 사용하는 것은 좋지 않습니다.은 서이옵 수있다니습에서 할 수 .FormControl
처음부터 시작할 때
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();
this.form.enable()
this.form.disable()
또는 폼 컨트롤 '먼저'
this.form.get('first').enable()
this.form.get('first').disable()
초기 세트에서 비활성화 또는 활성화를 설정할 수 있습니다.
first: new FormControl({disabled: true}, Validators.required)
그disabling
양제prevents
그것이 어떤 형태로 존재하는 동안.saving
설면됩니다로 .readonly
소유물.
다음과 같은 방법으로 이를 달성할 수 있습니다.
HTML:
<select formArrayName="value" [readonly] = "disableSelect">
TypeScript:
this.disableSelect = true;
세부 정보는 여기에 있습니다.
좀 더 일반적인 접근법이 될 것입니다.
// 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'
});
}
을 사용하지 first
(양식 제어) 그런 다음 아래 문장을 사용할 수 있습니다.
this.form.first.disable();
사용할 경우disabled
양식 입력 요소(정답에 제시된 것처럼 입력을 비활성화하는 방법)에 대한 유효성 검사도 비활성화됩니다. 주의하십시오!
(그리고 만약 당신이 제출 버튼을 사용한다면 다음과 같습니다.[disabled]="!form.valid"
필드가 유효성 검사에서 제외됩니다.)
» disabled
FormControl 내부의 true 속성은 확실히 입력 필드를 비활성화합니다.
this.form=this.fb.group({
FirstName:[{value:'first name', disabled:true}],
LastValue:['last name,[Validators.required]]
})
는 " 의▁the다"를 합니다.FirstName
입력 필드
된 필드 하려고 할 때합니다.console.log(this.form.value.FirstName);
그리고 그것은 보여줍니다.undefined
인쇄 필드의 실제 값 대신.사용할 수 없는 값에 비성화된필값액에려면합다사니다야용해음을하세활스를 해야 합니다.getRawValue()
에서 제공하는 Reactive Forms
를 들어, 예를 들어.console.log(this.form.getRawValue().FirstName);
폼 필드의 실제 값을 인쇄하며 정의되지 않았습니다.
이것은 저에게 효과가 있었습니다.this.form.get('first').disable({onlySelf: true});
최상의 솔루션은 다음과 같습니다.
솔루션 개요(링크가 끊어진 경우):
지시문 만들기
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 ) {}
}
그렇게 사용하세요.
<input [formControl]="formControl" [disableControl]="condition">
비활성화된 입력은 제출 시 form.value에 표시되지 않으므로 다음을 대신 사용해야 할 수도 있습니다(필요한 경우).
onSubmit(form) {
const formValue = form.getRawValue() // gets form.value including disabled controls
console.log(formValue)
}
그냥 사용하는 것입니다.
<input type="text" formControlName="firstName" [attr.disabled]="true || null" />
이와 함께.firstName
에서 액세스 가능한 상태 유지form.value
중요:사용해야 합니다.|| null
각도가 속성을 모두 제거할 수 있도록 기본값으로 설정합니다.
lastName: new FormControl({value: '', disabled: true}, Validators.compose([Validators.required])),
양식 그룹이 있는 경우 양식 그룹만 표시합니다.그러면 모든 양식 컨트롤이 비활성화됩니다.
formGroup = new FormGroup({
firstName: new FormControl(''),
lastName: new FormControl(''),
});
this.formGroup.disable();
저도 같은 문제가 있었지만, 이것을 호출하면 .form.controls['name']입니다.(router.navigate()를 사용하여) 보기를 다시 로드하는 중이었기 때문에 disable()이 수정되지 않았습니다.
이 경우 다시 로드하기 전에 양식을 재설정해야 했습니다.
this.form = 정의되지 않았습니다. this.filename.filename([path]);
로컬 저장소에서 값을 가져오려고 했고 전자 메일 및 암호 필드를 사용하지 않도록 설정하려고 했습니다.이것은 저에게 효과가 있었습니다.
email: new FormControl({value: localStorage.getItem("email"), disabled:true},[
Validators.required,
Validators.minLength(3),
]),
password: new FormControl({value: localStorage.getItem("password"), disabled:true},[
Validators.required,
Validators.minLength(3),
])
각도 14+
field = new FormControl<any>()
readonly formGroup = new FormGroup<any>({
field2: new FormControl<any>(),
});
옵션 1
ngOnInit() {
# ...
this.field.setDisable();
this.field.setEnable();
this.formGroup.controls.field2.setEnable();
this.formGroup.controls.field2.setDisabled();
# ...
}
옵션 2
private setFieldEnabled() {
this.field.setEnable()
}
private setFieldDisabled() {
this.field.setDisable()
}
private setField2Enabled() {
this.formGroup.controls.breakdown.setEnable();
}
private setField2Disabled() {
this.formGroup.controls.breakdown.setDisable();
}
setEnableOrDisableFields(truth: boolean): void {
if (truth) {
this.setFieldEnabled()
this.setField2Enabled();
return
}
this.setFieldDisabled()
this.setField2Disabled();
}
반응형에서 비활성화된 속성을 사용하여 입력 제어를 비활성화할 수 없습니다.이에 대한 가장 좋은 해결책은 필드 세트 요소를 추가하고 입력 컨트롤을 필드 세트 요소에 삽입하는 것입니다.그런 다음 유형 스크립트를 사용하여 필드 집합 요소를 쉽게 비활성화하거나 활성화할 수 있습니다.
예를 들면.
색인.
<fieldset [disabled]="variable_name">
<input name="name" formcontrolname="name">
</fieldset
index.
variable_name:boolean;
if(condition):
{
variable_name=true;
}
else
{
variable_name=false;
}
이렇게 하면 입력 컨트롤을 동적으로 숨기거나 표시하는 데 도움이 됩니다.
다음과 같이 .ts 파일에서 코딩하지 않고 HTML의 확인란이나 라디오에 대해 tr.disabled를 사용할 수도 있습니다.
<input type="checkbox" id="hasDataACheck" formControlName="hasDataA" /> <label class="form-check-label" for="hasDataACheck"> has Data A </label> <input type="text" formControlName="controlA" [attr.disabled]=" form.get('hasDataA').value ? null : '' />
필드를 비활성화하고 반응형 각 2+를 활성화하려면 다음과 같이 하십시오.
1. 비활성화하기
- [특성 사용 안 함] 추가= 입력에 "참"입니다.
<input class="form-control" name="Firstname" formControlName="firstname" [attr.disabled]="true">
활성화하기
export class InformationSectionComponent {
formname = this.formbuilder.group({
firstname: ['']
});
}
전체 양식 사용
this.formname.enable();
특정 필드만 사용
this.formname.controls.firstname.enable();
사용 안 함과 동일하게 enable()을 disable()로 바꿉니다.
이것은 잘 작동합니다.쿼리에 대한 설명입니다.
ReactiveForm을 만드는 동안:[FormControl에서 disballed된 속성 정의]
'fieldName'= new FormControl({value:null,disabled:true})
html:
<input type="text" aria-label="billNo" class="form-control" formControlName='fieldName'>
모든 양식 제어를 활성화/비활성화하는 기능을 선언할 수 있습니다.
toggleDisableFormControl(value: Boolean, exclude = []) {
const state = value ? 'disable' : 'enable';
Object.keys(this.profileForm.controls).forEach((controlName) => {
if (!exclude.includes(controlName))
this.profileForm.controls[controlName][state]();
});
}
그리고 이것을 이렇게 사용합니다.
// disbale all field but email
this.toggleDisableFormControl(true, ['email']);
당신은 CSS 클래스를 추가하고 각도로 바인딩하여 쉽게 할 수 있습니다.
.disable{
pointer-events: none;
}
<div [ngClass]="{'disable': //condition goes here">
<input type="text" formControlName="test">
</div>
언급URL : https://stackoverflow.com/questions/42840136/disable-input-fields-in-reactive-form
'programing' 카테고리의 다른 글
mongodump가 지정된 일부 컬렉션을 무시합니다. (0) | 2023.05.16 |
---|---|
System.web.mvc가 없습니다. (0) | 2023.05.16 |
디스플레이 없이 VBA로 읽을 수 있도록 Excel 파일 열기 (0) | 2023.05.16 |
AWS-lambda, Azure 함수 및 Google Cloud 함수 비교 (0) | 2023.05.16 |
VB의 숨겨진 특징.NET? (0) | 2023.05.16 |