我对Angular还是比较陌生的,这个嵌套的JSON的逻辑让我变得更好了,所以我道歉。
我希望创建一个动态表单,并使用this tutorial作为起点。
我正在尝试构建条件字段,只有当用户选择某个选项时才会显示。我希望它能够工作,这样,如果我的任何选项在数组中定义了子项,则会出现一个以这些子项作为选项的后续输入。我仍然有很多事情要考虑,但现在我正在尝试让它,以便当用户选择选项2时,选项2A和选项2B自动出现在下面的另一个下拉列表中。
如何创建一个ngIf*语句,声明“如果当前选择的选项有子选项,则将它们添加到另一个输入”?
我已经尝试过检查“tried”的数组长度是否大于零,还创建了一个名为"hasChildren“的布尔值,并手动分配一个true/false值进行检查(尽管我不喜欢这种解决方案,因为完成的应用程序将有许多嵌套选项,只检查数组是否为空会更容易)。
我也尝试过this solution,但肯定有一个语法错误,因为它对我不起作用。
HTML:
<ng-template [ngSwitchCase]="'select'">
<div class="form-group">
<label [for]="input.controlName"> {{input.controlName}}</label>
<select [formControlName]="input.controlName" [name]="input.controlName" [id]="input.controlName"
[required]="input.validators.required">
<option value="">{{input.placeholder}}</option>
<option *ngFor="let option of input.options" [value]="option.value">{{option.optionName}}</option>
</select>
</div>
<div *ngIf="this.input.options.children > 0" class="form-group">
<label [for]="input.options.optionName">{{input.options.optionName}}</label>
<select [formOptionName]="input.options.children.childName" [name]="input.options.children.childName" [id]="input.options.children.childName">
<option *ngFor="let children of input.options.children" [value]="children.value">{{children.childName}}</option>
</select>
</div>
</ng-template>form-data.ts
export interface FormData {
controlName: string;
controlType: string;
valueType?: string;
currentValue?: string;
placeholder?: string;
options?: Array<{
optionName: string;
value: string;
hasChildren: boolean;
children: Array<{
childName: string;
childValue: string;
}>
}>;
validators?: {
required?: boolean;
minlength?: number;
maxlength?: number;
};
}mock-form.ts
import { FormData } from './../interface/form-data';
export const MockForm: FormData[] = [
{
controlName: 'Options',
placeholder: 'Choose an option',
controlType: 'select',
options: [{
optionName: 'Option 1',
value: 'option 1',
hasChildren: false,
children: []
},
{
optionName: 'Option 2',
value: 'option 2',
hasChildren: true,
children: [{
childName: 'Option 2A',
childValue: 'option 2a',
},
{
childName: 'Option 2B',
childValue: 'option 2b'
}],
}],
validators: {
required: true
}
}
]当用户选择“Option2”时,我希望得到包含选项“Option2A”和“Option2B”的第二个下拉列表的输出,但我得到一个解析错误。
首先要感谢大家!
发布于 2019-08-02 14:16:15
我已经修改了你的代码,请检查:Your updated code sandbox code
发布于 2019-08-02 18:06:10
我认为你正在寻找级联下拉菜单。上面的解决方案可能会帮助你检查它。
https://stackoverflow.com/questions/57319809
复制相似问题