programing

Form control valueChanges는 이전 값을 제공합니다.

jooyons 2023. 8. 13. 09:40
반응형

Form control valueChanges는 이전 값을 제공합니다.

이름이 있는 양식 컨트롤이 있습니다.'question1'양식 개체 내에parentForm그리고 저는 다음과 같은 방법으로 구독했습니다.

두 가지 옵션이 있는 라디오 버튼입니다.Yes그리고.No내가 선택할 때No알겠습니다Yes그리고 내가 선택할 때Yes그것은 aNo.

this.parentForm.controls['question1'].valueChanges.subscribe(
  (selectedValue) => {
    // If option `No is selected`
    console.log(selectedValue);  // displays No. OK
    console.log(this.parentForm.value['question1']);  // displays Yes. Problem is here
  }
);

selectedValue변수의 값이 올바르지만 내가 그렇다면console.log(this.parentForm.value['question1']이전 값을 제공합니다.

나는 그것을 넣으려고 노력했습니다.setTimeout()값을 검색하기 전에this.parentForm.value['question1']그냥 잘 작동합니다.

setTimeout(() => {
  console.log(this.parentForm.value['question1']); // gives the correct value.
}, 500);

하지만 제 질문은 왜parentForm컨트롤의 값이 변경될 때 업데이트되지 않으며 값이 변경된 후에만 값을 검색합니다.

참고: 다음 기간 동안 관찰하지 않습니다.parentForm.valueChanges내 요구 사항이 아닙니다.

valueChanges파이프로 연결할 수 있도록 관찰 가능합니다.pairwise헤드라인 등록의 이전 및 다음 값을 가져옵니다.

// No initial value. Will emit only after second character entered
this.form.get('fieldName')
  .valueChanges
  .pipe(pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );
// Fill buffer with initial value, and it will emit immediately on value change
this.form.get('fieldName')
  .valueChanges
  .pipe(startWith(null), pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );

StackBlitz에서 작동하는 예: https://stackblitz.com/edit/angular-reactive-forms-vhtxua

갱신하다

만약 당신이 그것을 알아차리고 있다면.startWith권장되지 않는 것으로 보입니다. 그렇지 않습니다.답변에서 읽을 수 있는 운영자에 대한 활성 서명은 하나뿐입니다.

startWith(null) 또는 startWith(undefined)를 사용하고 있을 가능성이 매우 높습니다. 알림에도 불구하고 이들은 더 이상 사용되지 않지만 IDE가 잘못된 함수 서명을 감지하여 경고를 표시합니다.

간단한 해결 방법은 예상되는 반품 유형을 제공하는 것입니다.

// Prevent deprecation notice when using `startWith` since it has not been deprecated
this.form.get('fieldName')
  .valueChanges
  .pipe(startWith(null as string), pairwise())
  .subscribe(([prev, next]: [any, any]) => ... );

StackBlitz에서 함께 작동하는 예startWith: https://stackblitz.com/edit/angular-reactive-forms-rvxiua

valueChanges이벤트는 새 값이 업데이트된 에 실행됩니다.FormControl가치, 그리고 변화가 부모와 조상에게 거품이 되기 전에.따라서, 당신은 그 가치에 접근해야 할 것입니다.FormControl그 자체(방금 패치가 적용됨), 필드가 아닙니다.FormGroupvalue 객체(이벤트 중에는 변경되지 않음).

그것에 비추어 볼 때, 사용.this.parentForm.get('question1').value대신:

this.parentForm.controls['question1'].valueChanges.subscribe(
    (selectedValue) => {
      console.log(selectedValue);
      console.log(this.parentForm.get('question1').value);     
    }
);

시도해 보십시오.

this.parentForm.controls['question1'].valueChanges.subscribe(
    (selectedValue) => {
      console.log(selectedValue);
      console.log(this.parentForm.value.question1);     
    }
);

FormBuilder의 컨트롤이 업데이트된 경우 FormBuilder 개체에서 속성 값을 통해 마지막 값을 즉시 복구할 수 있습니다.

한 가지 옵션이 더 있지만 모든 경우에 적합하지 않을 수 있습니다. 한 의 체크 표시를 기다렸다가 다음 작업을 수행할 수 있습니다.selectedValueFormControl에서 업데이트됨:

setTimeout( () => console.log( selectedValue ) );

동기화/비동기화 양식에 대한 자세한 내용 항목:Angular Guide 문서의 반응형입니다.

사용 안 함:

 this.parentForm.controls['question1'].valueChanges.subscribe

사용:

this.parentForm.get('question1').valueChanges.subscribe

언급URL : https://stackoverflow.com/questions/44898010/form-control-valuechanges-gives-the-previous-value

반응형