【发布时间】:2019-04-02 18:55:18
【问题描述】:
我有一个包含四个选择字段的表单。分别是分支、学期和学科。我想根据所选的分支和学期显示主题选项列表。我应该创建哪种类型的 JSON 或数组?以及如何在 Angular 7 中使用 *ngFor 循环。
【问题讨论】:
标签: arrays json angular angular6 angular7
我有一个包含四个选择字段的表单。分别是分支、学期和学科。我想根据所选的分支和学期显示主题选项列表。我应该创建哪种类型的 JSON 或数组?以及如何在 Angular 7 中使用 *ngFor 循环。
【问题讨论】:
标签: arrays json angular angular6 angular7
通过订阅 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>
如果你不想做很多 if else,你可以设置你的选项看起来像这样。
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 遍历此对象的关卡。
【讨论】:
branch = { sem: [{subject: [...subjects]}]}你能告诉我你的模型吗?