首页 文章

将ngFor和ngModel与自定义模型一起使用时出现问题

提问于
浏览
0

带有ngFor和trackBy的ngModel:trackByIndex未按预期工作 . 这是我的html模板:

<form (ngSubmit)="createTest()" #testForm="ngForm">
            <div class="card" *ngFor="let question of questionsArr; let i=index;">
                <div class="card-header">
                    <input type="text" placeholder="Question {{i+1}}" name="question{{i}}"  class="form-control" [(ngModel)]="questionsArr[i].text">
                </div>
                <div class="card-block" *ngFor="let option of fillArray(oC); let u=index">
                    <input type="text" class="form-control" placeholder="Option {{u+1}}" name="option" id="option">
                </div>
            </div>
    </form>
The below works well. But in the above, [(ngModel)]="questionsArr[i].text" seems to bind to the same thing regardless.

<label *ngFor="let item of items; let i=index; trackBy:trackByIndex">
    {{items[i]}}
    <input type="number" [(ngModel)]="items[i]">
</label>.

我做了一些测试并使用了下面的对象数组的对象数组,它的作用应该是:

testarr = [
  {
    a: "a",
    b: "b"
  },
  {
    a: "aa",
    b:"bb"
  }
  ];

做一些测试,它的工作原理 . 将 ngModel 更改为 questionsArr[i] 也为每次迭代生成一个单独的对象 . 问题似乎是 [(ngModel)]="questionsArr[i].text" 不能正常运作 .

questionsArr只是一个数组:' new QuestionModel("Question Text", this.s.name, "",null); '

这是我组件的相关部分:

optionsArr: OptionModel[];
    questionsArr: QuestionModel[];

    blankQM: QuestionModel;
    blankOM: OptionModel;
    formTest: TestModel;

    items: number[] = [1,2,3,4,5];

  constructor(
    private api: ApiService
  ) { }

  ngOnInit() {
    this.blankQM = new QuestionModel("Question Text", this.s.name, "",null);
    this.blankOM = new OptionModel("Option Text");
    this.formTest = new TestModel("", null);
    this._getQuestionArrays();
    this._getOptionArrays();
  }

  _getQuestionArrays(){
    // this.fillArray(this.qC);
    this.questionsArr = Array(this.qC).fill(this.blankQM);
  }

  _getOptionArrays(){
    // this.fillArray(this.oC);
    this.optionsArr = Array(this.oC * this.qC).fill(this.blankOM);
    }

  fillArray(qty){
    return Array(qty).fill(0).map((e,i)=> i+ 1);
  }

  goBack(){
    this.back.emit();
  }

  createTest(){
    console.log(this.questionsArr);
    // console.log(this.optionsArr);

    console.log(this.testarr);
  }


  trackByIndex(index: number, value: QuestionModel){
    return index;
  }

  testarr = [
  {
    a: "a",
    b: "b"
  },
  {
    a: "aa",
    b:"bb"
  }
  ];
}

从我've gathered i' m使用 trackBy ,它做了它的假设,我不知道为什么我不能 ngModel 它绑定到正确的 questionsArr[i].text 访问 questionsArr 正确索引的text属性作为访问questionsArr enter code here 工作正常足够 .

1 回答

  • 0

    结果证明了

    Array.fill

    我做的是问题 . 更改了我的代码以使用for循环来填充数组 .

相关问题