programing tip

반응 양식-비활성화 된 속성

itbloger 2020. 10. 30. 07:47
반응형

반응 양식-비활성화 된 속성


에서 disabled속성 을 사용하려고 합니다 formControl. 템플릿에 넣으면 작동합니다.

<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>

그러나 브라우저는 다음과 같이 경고합니다.

반응 양식 지시문과 함께 disabled 속성을 사용하고있는 것 같습니다. 구성 요소 클래스에서이 컨트롤을 설정할 때 disabled를 true로 설정하면 disabled 속성이 실제로 DOM에 설정됩니다. '확인 후 변경'오류를 방지하려면이 방법을 사용하는 것이 좋습니다.

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

그래서 나는 그것을에 넣고 FormControl템플릿에서 삭제했습니다.

constructor(private itemsService: ItemsService) {
    this._items = [];
    this.myForm = new FormGroup({
        id: new FormControl({value: '', disabled: true}, Validators.required),
        title: new FormControl(),
        description: new FormControl()
    });
    this.id = this.myForm.controls['id'];
    this.title = this.myForm.controls['title'];
    this.description = this.myForm.controls['description'];
    this.id.patchValue(this._items.length);
}

그러나 작동하지 않습니다 (를 비활성화하지 않습니다 input). 무엇이 문제입니까?


나는 [attr.disabled]우수한 IMO이기 때문에 프로그래밍 방식 enable () / disable ()보다이 템플릿을 여전히 좋아하기 때문에 사용 하고 있습니다.

변화

<md-input formControlName="id" placeholder="ID" [disabled]="true"></md-input>

...에

<md-input formControlName="id" placeholder="ID" [attr.disabled]="true"></md-input>

최신 재료를 사용 md-input하는 경우 mat-input.


이 문제를 해결하려면 다음과 같이 시도 할 수 있습니다.

비활성화

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

활성화

this.myForm.controls['id'].enable();

자세한 내용은 https://github.com/angular/angular/issues/11271#issuecomment-244507976 과 관련하여 github에 게시 된 문제를 참조 하세요.


다음 방법을 사용하여 양식 컨트롤을 활성화 / 비활성화 할 수 있습니다.

control.disable () 또는 control.enable ()

그것이 효과가 없다면 지시문을 사용할 수 있습니다.

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]="disable">
<button (click)="disable = true">Disable</button>
<button (click)="disable = false">Enable</button>

이 기술은 여기에 설명되어 있습니다.

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

도움이되기를 바랍니다.


작동하려면 빈 문자열이더라도 기본값이 필요하다는 것을 알았습니다. 그래서 이거:

this.registerForm('someName', {
  firstName: new FormControl({disabled: true}),
});

...이되어야했습니다 :

this.registerForm('someName', {
  firstName: new FormControl({value: '', disabled: true}),
});

See my question (which I don't believe is a duplicate): Passing 'disabled' in form state object to FormControl constructor doesn't work


Initialization (component) using:

public selector = new FormControl({value: '', disabled: true});

Then instead of using (template):

<ngx-select
[multiple]="true"
[disabled]="errorSelector"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

Just remove the attribute disabled:

<ngx-select
[multiple]="true"
[(ngModel)]="ngxval_selector"
[items]="items"
</ngx-select>

And when you have items to show, launch (in component): this.selector.enable();


add name attribute to your md-input. if it doesn't solve the problem, please post your template


Use [attr.disabled] instead [disabled], in my case it works ok


add disable="true" to html field Example :disable

<amexio-text-input formControlName="LastName" disable="true" [(ngModel)]="emplpoyeeRegistration.lastName" [field-label]="'Last Name'" [place-holder]="'Please enter last name'" [allow-blank]="true" [error-msg]="'errorMsg'" [enable-popover]="true" [min-length]="2"
[min-error-msg]="'Minimum 2 char allowed'" [max-error-msg]="'Maximum 20 char allowed'" name="xyz" [max-length]="20">
[icon-feedback]="true">
</amexio-text-input>

The beauty of reactive forms is you can catch values changes event of any input element very easily and at the same time you can change their values/ status. So here is the another way to tackle your problem by using enable disable.

Here is the complete solution on stackblitz.


disabling of mat form fields is exempted if you are using form validation,so do make sure that your form field does not have any validations like(validators.required),this worked for me. for ex:

editUserPhone: new FormControl({value:' ',disabled:true})

this makes the phone numbers of user to be non editable.


Ultimate way to do this.

ngOnInit() {
  this.interPretationForm.controls.InterpretationType.valueChanges.takeWhile(()=> this.alive).subscribe(val =>{
    console.log(val); // You check code. it will be executed every time value change.
  })
}

참고URL : https://stackoverflow.com/questions/40494968/reactive-forms-disabled-attribute

반응형