首页 文章

Angular * ngFor with ngModel using Select具有意外绑定

提问于
浏览
2

我正在尝试为建筑行业的用户创建一个动态表单,该表单将基于每层分析建筑物(任意数量的楼层)的输入:

  • 用户最初会看到一个单层表单的表单,但是可以选择添加额外的层:

  • 我们应该能够添加任意数量的额外楼层,并根据需要删除特定楼层 .

Method

为了实现这一点,我正在尝试利用* ngFor并迭代一个将接收数据的数组,使用ngModel绑定到数组中的每个对象 .

component.html

<form *ngFor = "let storey of storeyData; let i = index; trackBy: trackByFn(i)">
    <md-select placeholder="Floor type" name ="floorTypeSelector{{i}}" [(ngModel)]="storeyData[i].floorTypes[0]">
        <md-option *ngFor="let floorType of floorTypes" [value]="floorType.value">
            {{floorType.viewValue}}
        </md-option>
     </md-select>

<button md-raised-button (click)="incrementStoreyNumber()">
    <md-icon>library_add</md-icon>
     Add storey
</button>

component.ts

export class FloorDetailsFormComponent implements OnInit {

selectedFloorType = [];
floorTypes = [
{value: 'concreteSlab', viewValue: 'Concrete slab'},
{value: 'suspendedTimber', viewValue: 'Suspended timber'},
{value: 'suspendedSlab', viewValue: 'Suspended slab'},
{value: 'wafflePod', viewValue: 'Waffle pod'}
]; 

storeyData = [{floorTypes: [],floorAreas:[] }];
storeyDataTemplate = {floorTypes: [], floorAreas:[]};

incrementStoreyNumber(){
    this.storeyData.push(this.storeyDataTemplate);
}

trackByFn(index){
 return index;
}
constructor() { }
ngOnInit() {
}

Problem

似乎前两层正确绑定了它们的变量,但是更改任何第二层到第n层的选定值将改变所有其他层(第一层除外) .

在搜索关于类似问题的其他帖子后,我仍然不知道为什么会发生这种情况 . 其他问题是,* ngFor循环的每次迭代都没有区分元素的名称,但是看看我的console.log,我可以看到每个元素的名称都应该被索引 .

我看到的一件有趣的事情是,如果我将storeyData数组扩展为typescript文件中n层的长度,那么所有层都将绑定到它们应该的自己的独立变量,并且所有的层都是n 1后来有同样的问题 .

我似乎也没有这个工作 . 我真的不了解's going on under the hood when I'试图在飞行中扩展* ngFor范围 . 也许这只是不好的做法?如果你能在这里帮助我,我将非常感激(即使它“嘿,读到这个”)

1 回答

  • 0

    问题出在这一行:

    this.storeyData.push(this.storeyDataTemplate);
    

    当你将storeyDataTemplate添加到storeyData时,每次你推送时绑定的是同一个对象,并且ngFor跟踪同一个对象 . 如果您更改为:

    this.storeyData.push({floorTypes: [], floorAreas:[]});
    

    它会工作 .

    DEMO

相关问题