geo*_*gej 6 typescript angular2-ngmodel angular
在我的TS文件中,我正在selectedValsObj像这样动态地在对象上创建属性:
private selectValsObj: any = {};
setSelectedValsObj(sectionsArr) {
sectionsArr.forEach(section => {
section.questions.forEach(questionObj => {
if (questionObj.type === 'drop-down') {
this.selectValsObj[questionObj.questionId] = { selected: questionObj.answerDetails[0] };
}
})
});
}
Run Code Online (Sandbox Code Playgroud)
在我的HTML中,我想将[ngModel]我的输入绑定到该selectValsObj对象的属性。我已经尝试过了,但是没有运气:
<div *ngFor="let question of section.questions">
<div class="drop-down-question" *ngIf="question?.type === 'drop-down'">
<select class="q-select"
[(ngModel)]="selectValsObj[questionId].selected" // <== doesnt work either**
// [(ngModel)]="selectValsObj[{{ questionId }}].selected" // <== doesnt work**
name="answerForQuestion{{ question?.questionId }}">
<option *ngFor="let answer of question?.answerDetails"
[ngValue]="answer">
{{ answer?.value }}
</option>
</select>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如何ngModel在HTML中将TS 设置为TS文件中动态创建的属性?
我试图复制这种情况,但在代码中,您发布的似乎是多个问题。
selectValsObj被声明为private但您试图在模板中使用它section.questions但我没有看到它在其他任何地方定义,而是在setSelectedValsObjforEach 本地范围的方法中这是我理解的代码并添加了 typedef
interface QuestionModel {
type: string;
questionId: string;
answerDetails: string[];
}
const MOCK_DATA = [
{
questions: [{
type: 'drop-down',
questionId: '42',
answerDetails: ['wololo'],
}],
},
];
@Component(...)
export class ProductsComponent {
selectValsObj: { [key: string]: { selected: string } } = {};
constructor() {
this.setSelectedValsObj(MOCK_DATA);
}
setSelectedValsObj(sectionsArr: { questions: QuestionModel[] }[]) {
sectionsArr.forEach(section => {
section.questions.forEach(questionObj => {
if (questionObj.type === 'drop-down') {
this.selectValsObj[questionObj.questionId] = {selected: questionObj.answerDetails[0]};
}
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
在您检查类型定义是否符合您最初的预期(并正确使用它)之后,您将防止许多错误。
此外,请考虑使用更多声明性方法,map而filter不是forEach在方法中使用您的数据。
| 归档时间: |
|
| 查看次数: |
4315 次 |
| 最近记录: |