내 응용 프로그램에서 각도 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
는 선택 사항입니다, 나는 당신의 문제를 이해하는 경우 나 코드가 작동
너무 게으른 게 아니라면 문제를 재현하는 플 런커를 만드는 것이 가장 좋습니다. 다음은 빈 각도 2 프로젝트입니다. https://angular.io/resources/live-examples/quickstart/ts/plnkr.html –
@StefanSvrkota 링크를 제공해 주셔서 감사합니다! [plunker] (http://plnkr.co/edit/pYp0KASufq2RW6cWADRL?p=preview)를 만들었습니다. – user3595026
지금 코드를보고 있지만 문제가 무엇인지 잘 모르겠습니다. 몇 마디로 설명해 주시겠습니까? :) –