2016-10-24 6 views
2

내 응용 프로그램에서 각도 2 모델 구동 양식을 사용하려고하지만 null 값이 포함 된 중첩 개체가 있으면 원하는대로 작동하지 못합니다.중첩 된 TypeScript 모델 객체와 Angular2 반응 양식 사용

person.model.ts

export class Address{ 
    addressId: string; 
    street: string 
    city: string; 
    state: string; 
    zip: string 
} 

사람

import {Address} from './address.model'; 
export class Person{ 
    personId: string; 
    name: string 
    age: number; 
    address: Address; 
} 

address.model.ts (이 중첩 된 객체로 주소를 가진 사람 모델 객체이다) : 여기

내 코드입니다 .component.ts

@Component({ 
selector: 'app-person', 
templateUrl: 'person.component.html' 
}) 
export class PersonComponent implements OnInit { 
personForm: FormGroup; 
person: Person; 

constructor(private someService: PersonService, private formBuilder: FormBuilder) {}  

ngOnInit(){ 
    this.someService.getPersonCall(personId) 
     .subscribe (person => { 
      this.person = person; 
      this.buildForm(); 
     } 
}; 

buildForm(): void { 
    this.personForm = this.formBuilder.group ({ 
     'name': [this.person.name, [Validator.required]], 
     'age': [this.person.age], 
     'street': [this.person.address.streetOne], 
     'city': [this.person.address.streetOne], 
     'state': [this.person.address.state], 
     'zip': [this.person.address.zip], 

    }); 
    this.registerForChanges(); 
} 

registerForChanges(): void { 
    this.personForm.get('name').valueChanges.subscribe(value => this.person.name=value); 
    this.personForm.get('age').valueChanges.subscribe(value => this.person.age=value); 
    this.personForm.get('street').valueChanges.subscribe(value => this.person.address.streetOne=value); 
    this.personForm.get('city').valueChanges.subscribe(value => this.person.address.city=value); 
    this.personForm.get('state').valueChanges.subscribe(value => this.person.address.state=value); 
    this.personForm.get('zip').valueChanges.subscribe(value => this.person.address.zip=value); 
} 


onSubmit() { 
    this.someService.update(this.person).subscribe(response => 
    this.person = response); 
} 

여기 내 person.component.html

<form *ngIf="person" (ngSubmit)="onSubmit()" [formGroup]="personForm" 
      novalidate> 
    <div class="col-md-6"> 
     <div class="form-group"> 
      <label for="nameId">Name</label> 
      <input type="text" class="form-control" formControlName="name" id="nameId"/>  
     </div> 
     <div class="form-group"> 
      <label for="ageId">Age</label> 
      <input type="number" class="form-control" formControlName="age" id="ageId"/>  
     </div> 
    </div> 
    <div class="col-md-6"> 
     <div class="form-group"> 
      <label for="streetId">Street</label> 
      <input type="text" class="form-control" formControlName="street" id="streetId"/>  
     </div> 
     <div class="form-group"> 
      <label for="cityId">City</label> 
      <input type="text" class="form-control" formControlName="city" id="cityId"/>  
     </div> 
     <div class="form-group"> 
      <label for="stateId">State</label> 
      <input type="text" class="form-control" formControlName="state" id="stateId"/>  
     </div> 
     <div class="form-group"> 
      <label for="zipId">Zip</label> 
      <input type="text" class="form-control" formControlName="zip" id="zipId"/>  
     </div> 
    </div> 

    <button type="submit" [disabled]="!personForm.valid">Save </button> 

</form> 

내가 서비스 호출에서 채워진 사람 개체를 업데이트하기 위해 노력하고 있어요,하지만 난 검색 할 때 사람이 사람 개체가 주소 속성에 null 값을 가지고 객체입니다 그리고 그것은 buildForm 함수 내 코드를 위반합니다.

나는 다른 방법의 몇 가지를 시도했지만 수 없습니다 그것은 내가 어떤 오류없이 양식을 렌더링 할 수 있었다 이러한 변화와 함께

버전 # 2

buildForm(): void { 
if (!this.person.address) { 
    this.personForm = this.formBuilder.group ({ 
     'name': [this.person.name, [Validator.required]], 
     'age': [this.person.age], 
     'street': [''], 
     'city': [''], 
     'state': [''], 
     'zip': [''], 

    }); 
} else { 
    this.personForm = this.formBuilder.group ({ 
     'name': [this.person.name, [Validator.required]], 
     'age': [this.person.age], 
     'street': [this.person.address.streetOne], 
     'city': [this.person.address.streetOne], 
     'state': [this.person.address.state], 
     'zip': [this.person.address.zip], 

    }); 
} 

    this.registerForChanges(); 
} 

을 작동하도록,하지만 난 때 registerForChanges 함수에서 실패한 모든 주소 필드를 업데이트합니다.

내가 주소 필드를 변경하지 않고 양식을 저장할 때 주소 테이블에 빈 레코드를 추가 결국이 변경 이후 버전 # 3

registerForChanges(): void { 

if (! person.address) { 
    person.address = new Address();  
this.personForm.get('name').valueChanges.subscribe(value => this.person.name=value); 
this.personForm.get('age').valueChanges.subscribe(value => this.person.age=value); 
this.personForm.get('street').valueChanges.subscribe(value => this.person.address.streetOne=value); 
this.personForm.get('city').valueChanges.subscribe(value => this.person.address.city=value); 
this.personForm.get('state').valueChanges.subscribe(value => this.person.address.state=value); 
this.personForm.get('zip').valueChanges.subscribe(value => this.person.address.zip=value); 
} 

.

이 코드는 함수의 address 속성이 null이 아닌 경우 제대로 작동합니다.

사람은 address는 선택 사항입니다, 나는 당신의 문제를 이해하는 경우 나 코드가 작동

plunker link

+0

너무 게으른 게 아니라면 문제를 재현하는 플 런커를 만드는 것이 가장 좋습니다. 다음은 빈 각도 2 프로젝트입니다. https://angular.io/resources/live-examples/quickstart/ts/plnkr.html –

+0

@StefanSvrkota 링크를 제공해 주셔서 감사합니다! [plunker] (http://plnkr.co/edit/pYp0KASufq2RW6cWADRL?p=preview)를 만들었습니다. – user3595026

+0

지금 코드를보고 있지만 문제가 무엇인지 잘 모르겠습니다. 몇 마디로 설명해 주시겠습니까? :) –

답변

1

을 할 수 있습니다.

  1. 양식이로드 더 address (이 null있어)이없고 아무것도 address 값 (Street, City, State 또는 Zip)에 추가되어 있지 않은 경우, 당신이 원하는 : 두 가지 시나리오는 커버 할 수 있습니다 저장

  2. 을 클릭하면이 null을 유지하기 위해 더 address (이 null을의) 뭔가 address 가치있는 추가하면 폼이로드 될 때 this.person.addressnull 동일한 경우 확인 buildForm() 기능에 - ES (Street, City, State 또는 Zip, 당신은 당신이처럼 그것을 달성 할 수있는이 값

을 저장할. 이 경우, 새로운 Address를 만듭니다

buildForm(): void { 

     if (!this.person.address) { 
     this.person.address = new Address(); 
     } 
    } 

addressnull 때 양식을 만들 때 온다 오류를 방지 할 수 있습니다. 다음 단계는 this.person.address 값이 여전히 null 또는 '' (빈 문자열)인지 확인하기 위해 onSubmit() 함수에서 사용될 함수를 만드는 것입니다. 그럴 경우 함수는 this.person.addressnull으로 설정하고 빈 Address 개체는 저장하지 않고 대신 null이됩니다. null이 아닌 경우 값이 삽입 된 Address 개체가 저장됩니다.

checkAddress(): void { 
    if (this.person.address.street == null | this.person.address.street == '' && 
     this.person.address.city == null | this.person.address.city == '' && 
     this.person.address.state == null | this.person.address.state == '' && 
     this.person.address.zip == null | this.person.address.zip == '') { 
     this.person.address = null; 
     } 
} 

을 그리고 마지막으로, 당신은 기능 onSubmit()에 기능 checkAddress를 호출 할 필요가 :의 그 기능을 checkAddress()를 부르 자

onSubmit() { 
    console.log('On Save') 
    this.checkAddress(); 
    console.log(this.person); 
    console.log(this.person.address); 
} 

여기 working Plunker을합니다.

if (!this.person.address) { 
    this.person.address = new Address(); 
} 

희망이 -

주 먼저 빈 값으로 저장을 클릭 한 다음 몇 가지 값을 삽입하려고하면 나는 오류를 방지하기 위해 onSubmit() 함수에서 "저장"코드 아래에 다음 코드를 추가 도움이됩니다. 건배.

+0

노력에 감사드립니다! 폼을 개발할 때이 옵션을 살펴 보았지만 이와 같은 코드는 유지하기 어렵습니다 (향후 주소 모델에 더 많은 속성을 추가하려는 경우 실제 응용 프로그램의 자식 객체는 많은 속성을가집니다). 'checkAddress()'함수를 사용하지 않고 다른 방법이 있습니까? – user3595026