Angular 2-具有动态对象/属性的ngModel

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文件中动态创建的属性?

Voj*_*ech 5

我试图复制这种情况,但在代码中,您发布的似乎是多个问题。

  1. 属性selectValsObj被声明为private但您试图在模板中使用它
  2. 在您尝试迭代的模板中,section.questions但我没有看到它在其他任何地方定义,而是在setSelectedValsObjforEach 本地范围的方法中
  3. 由于缺乏类型定义,您可能会错误地使用您的数据

这是我理解的代码并添加了 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)

在您检查类型定义是否符合您最初的预期(并正确使用它)之后,您将防止许多错误。

此外,请考虑使用更多声明性方法,mapfilter不是forEach在方法中使用您的数据。