2017-04-05 1 views
0

아래 양식과 몇 가지 기능이 있습니다.각도 2는 patchValue를 사용하여 REST API에서 데이터를 설정합니다.

ngOnInit() { 
     this.buildForm(); 
     this.loadData(); 
     this.success = false; 
    } 

    loadData(): void { 
     this.countryService.getCountries().subscribe(list => { 
      this.countries = new Select2Mapper('countryCode', 'name').getData(list); 
      this.setDefaultCountry(); 
     }); 
    } 

    setDefaultCountry(): void { 
     console.log('Setting default country'); 
     console.log(this.accountCreateForm.get('company').value); 
     this.accountCreateForm.get('company').patchValue({ 
      countryCode: "US" 
     }); 
    } 

    buildForm(): void { 

     this.accountCreateForm = this.fb.group({ 
      company: this.fb.group({ 
       companyName: ['', [WPValidator.companyName]], 
       countryCode: ['', [Validators.required]] 
      }), 
      administrative: this.fb.group({ 
       firstName: ['', [WPValidator.nameMandatory]] 
      }) 
     }); 

     console.log('Form built'); 

     this.accountCreateForm.valueChanges 
      .subscribe(data => this.onValueChanged(data)); 

     this.onValueChanged(); // (re)set validation messages now 

    } 

위 예제에서 buildForm 다음에 setDefaultCountry setDefaultTimeZone이 호출되는 것을 볼 수 있습니다. 새 값이 UI에 반영되는 이유를 이해할 수 없습니다. UI에서 볼 수있는 것은 값의 전체 목록입니다. 패치 값을 표시하지 않습니다. 기본값을 설정하기 전이나 후에 모든 이벤트를 트리거해야합니까?

또한 기본값 인 patchValue를 설정 한 후에 양식 값을 인쇄하면 업데이트 된 값을 볼 수 있습니다. 이 중요한 경우

, 나는 당신이() changeDetectionRef를 가져 detectChanges를 호출 할 필요가 아래로

+0

patchValue() 후 클래스 내부에 그런

import {ChangeDetectorRef} from '@angular/core'; 

,

constructor(private _cdr : ChangeDetectorRef){ } 

나중에 호출합니다. 그것도 잘 작동하지 않았다. – TechCrunch

+0

NgZone에도 행운이 없습니다. ( – TechCrunch

답변

0

드롭 국가 선택 2의 jQuery 플러그인에 각 래퍼를 사용하고 있습니다. 내가 패치 후 ChangeDetectorRef 전화를 시도 _cdr.detectChanges()

+0

질문에 언급 한대로 이전에 시도해 보았지만 작동하지 않았습니다. – TechCrunch

+0

@TechCrunch try''applicationRef.tick()'' – CruelEngine

+0

잘 작동하지 않았습니다. 도움이된다면 ,이 Select2 래퍼 - https://github.com/NejcZdovc/ng2-select2/issues/76 같이 사용하고 있습니다. – TechCrunch

관련 문제