[英]Angular 4 ngModel binding within nested *ngFor
您好,我遇到了一個問題,我無法將數據綁定到此嵌套* ngFor中作為“ Selected”值顯示的內容。 這里發生的事情是我列出了可能的害蟲(蟲子等)清單,對於每種害蟲,我都有要向該人員詢問的問題清單。 因此,當我遍歷每個選定的有害生物時,然后進入每個問題(某些有害生物具有相同的問題),它將一個有害生物的答案與所有其他具有相同問題的有害生物綁定在一起。 無論我嘗試什么,都不允許我將所選答案綁定到特定的有害生物,而不是其余的有害生物。 這是我的HTML:
這是我正在嘗試進行的工作的Stackblitz。 就像在堆疊閃電戰中一樣,我遇到了一系列的問題,這些問題被我推入了一系列的害蟲之中。
<div *ngFor="let each of selectedPestProblems; let x = index;">
<div *ngIf="selectedPest === x" class="pestQuestions">
<div *ngFor="let questions of each.question; let i = index; trackBy:trackByIndex">
<h4 *ngIf="i == 0" style="padding-left: 15px;"><br>{{each.pest}}</h4>
<label>{{questions.question}}</label>
{{x + " " + i}}
<div *ngIf="questions.type == 'checkbox'" (click)="changeCheckBox2(x, i)">
<input type="checkbox" class="css-checkbox" [(ngModel)]="selectedPestProblems[x].question[i].selected" name="checkbox{{i + '' + x}}">
<label class="css-label"> - {{questions.title}}</label>
</div>
<div *ngIf="questions.type == 'select'">
<select class="otherSelects" [(ngModel)]="selectedPestProblems[x].question[i].selected" name="select{{i + '' + x}}">
<option *ngFor="let answers of questions.answer" [value]="answers.id">
{{answers.name}}
</option>
</select>
</div>
<div *ngIf="questions.type == 'selectOther'">
<select class="otherSelects" [(ngModel)]="selectedPestProblems[x].question[i].selected" name="selectOther{{i + '' + x}}">
<option *ngFor="let answers of questions.answer" [value]="answers.id">
{{answers.name}}
</option>
</select>
<div *ngIf="questions.selected == 5">
<br>
<textarea [(ngModel)]="selectedPestProblems[x].question[i].description" placeholder="Tell Us Where It Is Located." name="description{{i + '' + x}}"></textarea>
</div>
</div>
<br>
<div *ngIf="i == selectedPestProblems[x].question.length - 1">
<button (click)="removePestProblem(x)" style="margin-left: 15px;">Remove Pest Problem</button>
<br>
</div>
</div>
</div>
</div>
這是我循環遍歷的數組的一個示例。
因此,此陣列僅顯示了我正在循環傳播的一種害蟲,底部還有另一種害蟲“蜜蜂”,發生的是我的復選框和選擇的框,我認為應該在其中對其進行建模每個害蟲的每個問題的“選定”值,但是當我為其中一個問題選擇一個答案時,它表明並未為所有其他具有相同問題的害蟲選擇該答案。
不要忘記,JavaScript / TypeScript對象是引用類型。 您將同一問題對象推入兩個不同的數組中,這並不意味着兩個對象都不同-兩個對象都相同-就內存位置而言,它們的位置相同。
您可以使用TypeScript的Object Spread運算符使對象彼此不同-它們是不同的(不同的內存位置)。
ngOnInit(){
for(var i = 0; i < this.selectedPestProblems.length; i++){
this.selectedPestProblems[i].question.push({...this.question1});
this.selectedPestProblems[i].question.push({...this.question2});
}
}
[只是說明,這是一個不同的層次]
我已經為您的stackblitz代碼提供了解決方案。 https://stackblitz.com/edit/angular-rphm3z?file=src/app/app.component.ts
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.