1

각도 4, 부트 스트랩 4 및 ngbootstrap을 사용하여 응용 프로그램을 개발 중입니다. HTML 코드 -ng-bootstrap에서 양방향 바인딩이 작동하지 않습니다

<div class="container"> 
    <form [formGroup]="myForm" novalidate (ngSubmit)="save(myForm.value)"> 
    <div class="form-group"> 
     <div class="row"> 
     <legend class="col-form-legend col-sm-2">Required</legend> 
     <div class="btn-group col-sm-2" ngbRadioGroup name="isRequired" formControlName="isRequired"> 
      <label ngbButtonLabel class="btn-primary"> 
      <input ngbButton type="radio" name="radio" [value]="true">Yes 
      </label> 
      <label ngbButtonLabel class="btn-primary"> 
      <input ngbButton type="radio" name="radio" [value]="false">No 
      </label> 
     </div> 
     </div> 
    </div> 
    <div class="form-group row"> 
     <div class="col-sm-6"> 
     <button type="submit" class="btn btn-info"> 
      <i class="fa fa-floppy-o fa-lg"></i> 
      Save 
     </button> 
     </div> 
    </div> 
    </form> 
</div> 

제어기는 I buildForm() 메소드를 호출 제어기의 ngOnInit() 후크

private buildForm() { 
    this.myForm = this.formBuilder.group({ 
     isRequired: [], 
    }); 
    } 

. 그런 다음 HTTP 요청을 만들고 isRequired 필드 값을 가져옵니다. 가져 오기가 성공하면 다음 메소드를 호출하여 라디오 버튼의 값을 설정합니다.

private loadFormData() { 
    this.myForm.patchValue({ 
     isRequired: this.variable.isRequired, 
    }); 
} 

문제 - 참 애드 팍 =의 값을 가정 할 수 있습니다. 이 값 이 제대로 가져오고 양식로드시이 값이 인 라디오가 초기화됩니다. 그러나 사용자가 값 (isRequired = false)을 변경하면 필드는 여전히 이전 값 (isRequired = true)을 유지합니다.

나는 다음과 같은 코드를 사용하는 경우이 잘 작동 -

<div class="form-group"> 
    <div class="row"> 
     <legend class="col-form-legend col-sm-2">Required</legend> 
     <input type="radio" formControlName="isRequired" value="true"> Yes 
     <input type="radio" formControlName="isRequired" value="false"> No 
    </div> 
</div> 

내가 잘못하고있는 중이 야 무엇을? 반응성에 대한 The data model and the form model 안내 사항에 따라

+0

https://angular.io/guide/reactive-forms#the-data-model-and-the-form-model – ranakrunal9

+0

@ ranakrunal9. 반응 형 라디오 버튼 예제를 본 링크에 표시되어 있습니다. -> https://ng-bootstrap.github.io/#/components/buttons/examples – codejunkie

답변

0

는 사용자가 라디오에서 값 귀하의 변수 this.variable.isRequired가 업데이트되지된다 선택할 때 즉

User changes flow from the DOM elements to the form model, not to the data model. The form controls never update the data model.

형성한다. 양식 값을 얻으려면 this.myForm.value을 사용하거나 ng-bootstrap buttons에 설명 된대로 ngModel을 라디오에서 사용해야합니다.

+0

this.variable은 데이터베이스에서 가져온 객체이며 라디오 버튼의 초기 값을 포함합니다. 양식이 저장되면 myForm.value.isRequired를 확인합니다. – codejunkie

+0

ngModel과 formControlName을 함께 사용할 수 있습니까? – codejunkie

관련 문제