我有类'CheckBoxQuestion'的对象实例。我需要为其属性赋值。有属性调用选项[],这里我正在组装类型清单的键值。现在我的问题是需要比较item.preDefineAnswerOptionId键值,即如果存在于数组中,为此我有单独的函数'contains(a,obj)我调用以获取布尔结果
这个包含函数适用于以下测试代码;
for(var item in questionsList[key].answer)
{
var dd = this.contains(questionsList[key].answer, questionsList[key].answer[item].answerValue)
}
但是当我为'optionSelected'属性执行时,它会抛出错误
else if(questionElementType=="checkbox")
{
let _checkBox = new CheckBoxQuestion ({
consultationId: questionsList[key].consultationId,
questionId: questionsList[key].questionId,
questionElementType: questionsList[key].questionElementType[0].title,
questionType: questionsList[key].questionType,
title:questionsList[key].title,
displayId: questionsList[key].displayId,
key: questionsList[key].questionId,
value: questionsList[key].answer.length<=0? null : questionsList[key].answer[0].answerValue.toLowerCase(),
label: questionsList[key].title,
order: 7,
options: questionsList[key].answerOptions.map(function(item){
return {"name": item.ReferenceKey, "key": item.preDefineAnswerOptionId, "value": item.text, "optionSelected": this.contains(questionsList[key].answer, item.preDefineAnswerOptionId)} // need help here, throw error
}),
});
this.mappedQuestions.push(_checkBox);
}
contains(a, obj)
{
let f:string[]=[];
if(a.length>0)
{
for(var item in a)
{
var answerKey = a[item].answerValue.toLowerCase();
f.push(answerKey)
}
var i = f.length;
while (i--) {
if (f[i] === obj.toLowerCase()) {
return true;
}
}
}
return false;
}
error 1-`formGroup expects a FormGroup instance. Please pass one in.`
error 2- Cannot read property 'contains' of undefined
答案 0 :(得分:0)
问题1:
您的form
应该是表单组的实例,请使用myForm: FormGroup;
<强>组件:强>
import {FormGroup, FormBuilder, Validators} from '@angular/forms';
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) {
this.myForm = this.formBuilder.group({
title: ['', [Validators.required, Validators.minLength(5)]],
description: [''],
});
}
<强> HTML 强>
<form [formGroup]="myForm" (ngSubmit)="logForm()">
问题2:
由于您使用的function
内部使用this
,因此无效。
如果是typescript
options: questionsList[key].answerOptions.map((item) => {
return {"name": item.ReferenceKey, "key": item.preDefineAnswerOptionId, "value": item.text, "optionSelected": this.contains(questionsList[key].answer, item.preDefineAnswerOptionId)} // need help here, throw error
}),
答案 1 :(得分:0)
你需要改变这个:
function(item) { ... }
使用箭头符号(保留this
引用):
(item) => { ... }
答案 2 :(得分:0)
我找到了答案,
options: questionsList[key].answerOptions.map(function(item){
return {"name": item.ReferenceKey, "key": item.preDefineAnswerOptionId, "value": item.text, "optionSelected": this.contains(questionsList[key].answer, item.preDefineAnswerOptionId)}
}.bind(this)),