我不断收到以下控制台错误:
Error trying to diff 'Paul'. Only arrays and iterables are allowed
Run Code Online (Sandbox Code Playgroud)
HTML:
<fieldset class="one-quarter sm-padding">
<label>Occupation</label>
<select name="occupations"
[(ngModel)]="occupations"
(ngModelChange)="showValuePromptText('Occupation', $event)">
<option *ngFor="let occupation of occupations"
[value]="occupation">
{{occupation}}
</option>
</select>
</fieldset>
Run Code Online (Sandbox Code Playgroud)
TS:
import { Component } from '@angular/core';
import { PromptService } from '../../services/prompt.service';
import { IPromptText } from "../../models/IPromptText";
@Component({
selector: 'fact-find',
templateUrl: './factfind.component.html',
styleUrls: ['./factfind.component.css'],
providers: [PromptService]
})
export class FactFindComponent {
promptTexts: IPromptText[];
currentPromptText : string;
showDefaultPromptText(fieldName: string) {
if (fieldName != null) {
this.promptService.fetchPrompts(fieldName, '').subscribe(
(data) => this.currentPromptText = data
);
}
}
showValuePromptText(fieldName: string, fieldValue: string) {
if (fieldValue != null) {
this.promptService.fetchPrompts(fieldName, fieldValue).subscribe(
(data) => this.currentPromptText = data
);
}
}
occupations: string[] = ["John", "Paul", "George", "Ringo"];
}
Run Code Online (Sandbox Code Playgroud)
如果有人能阐明我如何解决这个问题,将不胜感激。
Flo*_*oyd 13
正如其他人所指出的那样,问题就在[(ngModel)]="occupations"眼前。在我看来它应该是这样的[(ngModel)]="selectedOccupation"。换句话说,你需要绑定的[(ngModel)]在组成一个字符串变量。
考虑下面的例子,让我们分解它来理解这是说:
<select [(ngModel)]="selectedOccupation"
(ngModelChange)="test()">
<option *ngFor="let occupation of occupations"
[value]="occupation">
{{occupation}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
在此示例中,该[(ngModel)]="selectedOccupation"位假定selectedOccupation组件中存在变量。Using在 html 中元素的值(这将是当时选择的任何选项)和组件中变量的值之间[(ngModel)]创建双向绑定。换句话说,如果用户从 html 的选择菜单中选择“foo” ,则组件中变量的值将更改为“foo”(并且组件内部的更改将反映在 html 中)。我不打算介绍它的其余部分,因为这与问题无关,但其余代码的基本要点是它将在 select 语句中列出每个as 选项。<select>selectedOccupationselectedOccupationoccupations
要使您的代码正常工作,您只需要将 html 更改为:
<fieldset class="one-quarter sm-padding">
<label>Occupation</label>
<select name="occupations"
[(ngModel)]="selectedOccupation"
(ngModelChange)="showValuePromptText('Occupation', $event)">
<option *ngFor="let occupation of occupations"
[value]="occupation">
{{occupation}}
</option>
</select>
Run Code Online (Sandbox Code Playgroud)
其中selectedOccupation是组件中存在的字符串变量。
我刚换[(ngModel)]="occupations"到[(ngModel)]="selectedOccupation"。
| 归档时间: |
|
| 查看次数: |
35833 次 |
| 最近记录: |