如何将属性值(如果不为null)分配给TypeScript中的对象实例,Angular

时间:2018-04-10 09:18:09

标签: angular typescript

我循环遍历对象数组并创建特定类的实例,然后相应地分配值。一切正常,我希望我需要检查值是否存在然后才分配。

在我的场景中,我有可能会或可能没有回答的问题列表,以便检查并分配值,如果不为null,我执行以下代码但是抛出错误。

value: questionsList[key].answer.length>0? null : questionsList[key].answer[0].answerValue

完整代码

if(questionElementType=="textbox")
 {       

  var isAnswerExist = questionsList[key].answer.length;
  if(isAnswerExist>0) // this one does work
  {
    var ans = questionsList[key].answer[0].answerValue;
    console.log("answer  ", ans);
  }


   let _textBox = new TextboxQuestion({
     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, 
     label: questionsList[key].title,
     value: questionsList[key].answer.length>0? null : questionsList[key].answer[0].answerValue,  // need help here
     required: true,
     order: 5
    }); 

    this.mappedQuestions.push(_textBox);

 }

错误1

formGroup expects a FormGroup instance. Please pass one in.

   Example:


<div [formGroup]="myGroup">
  <input formControlName="firstName">
</div>

In your class:

this.myGroup = new FormGroup({
   firstName: new FormControl()
});

错误2

TypeError: Cannot read property 'answerValue' of undefined

3 个答案:

答案 0 :(得分:1)

你需要这样做

value: (questionsList 
       &&  questionsList[key].answer  
       && questionsList[key].answer.length>0) ? questionsList[key].answer[0].answerValue : null 

答案 1 :(得分:1)

你应该扭转你的状况,你会收到错误,

只有在数组长度为&gt;时才应添加值0

value: questionsList[key].answer.length > 0 ?  questionsList[key].answer[0].answerValue : null,  // need help here

完整代码

let _textBox = new TextboxQuestion({
     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, 
     label: questionsList[key].title,
     value: questionsList[key].answer.length > 0 ?  questionsList[key].answer[0].answerValue : null,  // need help here
     required: true,
     order: 5
    }); 

答案 2 :(得分:1)

你刚才犯了一个简单的错误

value: questionsList[key].answer.length>0? null : questionsList[key].answer[0].answerValue,  // need help here

应该是相反的

value: questionsList[key].answer.length>0?  questionsList[key].answer[0].answerValue : null ,