2016-11-28 1 views
1

"질문"을 만들 수있는 폼이 있습니다.이 폼은 답변 문자열 배열을 포함하는 개체입니다. 내 문제는 내가 순진 된 구현이 될 것이다 질문 모델json 개체에서 Angular2의 ngModel을 사용하여 폼에 바인딩합니다.

에 그 답을 결합 할 수있는 방법을 찾을 수 있다는 것입니다 :

import { Component } from '@angular/core'; 
class Question { 
    question: string; 
    answers: Array<string>; 
} 

@Component({ 
    selector: 'app', 
    template: ` 
<input type="text" [(ngModel)]="question.question"> 
<input type="text" *ngFor="let answer of question.answers" [(ngModel)]="answer"> 
` 
}) 

export class AppComponent { 
    question: Question = new Question; 
    question.answers = new Array(4); 
    constructor(){}; 
} 

문제는 두 번째 ngModel에 있습니다.

zone.js:388 Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: <root> ; Task: Promise.then ; Value: Error: Cannot assign to a reference or variable! 

나는 우리가 모델로 ngFor에서 생성 된 값을 바인딩 할 수 없습니다 추측 :이 솔루션을 가 나는 오류가 발생합니다.

  • [(ngModel)]="question.answers[index]" -> 제가 ngForlet index=index;에 첨가하고,이 입력에 대응하는 이름 :

    은 또한 이러한 옵션을 시도했다. 여기에 다음 단락에서 설명하는 오류가 있습니다.
  • [(ngModel)]="question.answers[] -> 순수 HTML을 사용하여 동일한 작업을 수행하려고합니다. 이것은 전혀 작동하지 않습니다

예상대로 작동하지 않았습니다. 입력 값을 변경하면 ngFor 루프가 다시로드 된 것 같습니다. 사용자가 답변을 추가하거나 삭제할 수 있도록 솔루션을 확장 한 경우 답변을 추가하면 첫 번째 콘텐츠가 삭제됩니다.

답변

4

는 최대한 멀리 볼 수있는 두 가지 옵션이 있습니다

1을 사용하여 객체 대신 배열을

여기에 설명 된 것처럼 당신은 ngFor와 파이프를 사용하여 객체를 반복 할 수 있습니다 Iterate over TypeScript Dictionary in Angular 2

@Pipe({ name: 'values', pure: false }) 
export class ValuesPipe implements PipeTransform { 
    transform(value: any, args: any[] = null): any { 
    return Object.keys(value).map(key => value[key]); 
    } 
} 

<div *ngFor="#value of object | values"> </div> 

2 사용 http://plnkr.co/edit/PO9ujHLWfzvYD67nDCwT?p=preview

여기 같은 ngFor 루프위한 제 2 어레이
import { Component } from '@angular/core'; 

export class Hero { 
    id: number; 
    name: string; 
} 

@Component({ 
    selector: 'my-app', 
    template: `<h1>Hello {{name}}</h1> 
    <div *ngFor="let count of dummyArr; let i=index"> 
    <input type="number" [(ngModel)]="data[i]"> 
    </div> 
    ` 
}) 
export class AppComponent implements OnInit { 
    name = 'Angular'; 
    data:number[]=[]; 
    dummyArr:number[]=[]; 

    ngOnInit(){ 
    this.data.length=6; 
    this.dummyArr.length=6; 
    } 
} 
+1

을 받기 ...이 사람이 두 번째 배열을했다,하지만 난 그것을 조금 이상한 찾을 ... http://plnkr.co/edit/PO9ujHLWfzvYD67nDCwT?p=preview 당신이 정말로 필요하십니까 배열 또는 객체를 반복 할 수 있습니까? 파이프를 작성하면 이렇게 할 수 있습니다. http://stackoverflow.com/questions/35534959/access-key-and-value-of-object-using-ngfor – Riscie

+0

두 가지 솔루션은 정말 좋은 조정할 수 있으며 내 문제를 해결할 수 있습니다. 멋지게). 그에 따라 응답을 편집하여 유효성을 검사 할 수 있습니다. 요소를 삭제하고 추가하고 있기 때문에 배열이 필요합니다. 0부터 length - 1까지 색인을 가져야합니다. 객체로 처리 할 수 ​​있지만 과도한 것처럼 보입니다. –