如何使用ngFor循环基于前两个选定值选择第三个值列表

时间:2019-04-02 18:55:18

标签: arrays json angular angular6 angular7

我有一个包含四个选择字段的表单。分院,学期和科目。我想根据所选的分支和学期显示主题选项列表。我应该创建哪种类型的JSON或数组?以及如何在角度7中使用* ngFor进行遍历。

1 个答案:

答案 0 :(得分:0)

通过订阅valueChanges来跟踪FormControl中每个字段OnInit的更改。

branch = ['Computer', 'Civil', 'Electronics','Mechanical' ];
semester = ['1st', '2nd', '3rd','4th','5th','6th', '7th', '8th'];
formGroup: FormGroup;
subjectOptions: [] = [];
constructor(private fb: FormBuilder) {}

ngOnInit(): void {
  // I like to use Formbuilder b/c the syntax is less verbose.
  this.formGroup = this.fb.group({
    branch: '',
    semester: '',
    subject: '',
  });

  this.formGroup.valueChanges.subscribe(newGroupValue => {
    // Match criteria
    if (newGroupValue.branch === 'Computer' && newGroupValue.semester === '3rd') {
      // However you want to generate a new array of options to display in select
      this.subjectOptions = [
       'C++','Data Structure','DE'
      ];
    }
  }
});

然后遍历新的选择选项。

您可以使选项数组成为具有名称和值属性的对象。然后对它们使用单​​向属性绑定。

<div [formGroup]="formGroup">
  // Rest of the dropdowns above w/ corresponding formControlName
  <select formControlName="subject">
     <option *ngFor="let option of subjectOptions" [name]="option.name" [value]="option.value"></option>
  </selct>
</div>

如果您不想做很多其他事情,可以将选项设置为如下所示。

const branches = {
    computer: {
        name: 'Computer',
        semesters: {
            third: {
                name: '3rd',
                subjects: {
                    c: {
                        name: 'C++'
                    },
                    'data-structure': {
                        name: 'Data Structure'
                    }
                }
            }
        }
    }
}

您可以使用Map对象...等...,只要可以通过键对其进行访问即可。

然后在订阅回调中对表单的valueChange进行更改:

this.formGroup.valueChanges.subscribe(newGroupValue => {
   if (newGroupValue.branch && newGroupValue.semester) {
      this.subjectOptions = branches[newGroupValue.branch].semesters[newGroupValue.semester].subjects;
   }
}

从那里,您可以使用KeyValuePipe遍历此对象的级别。