【发布时间】:2019-08-02 04:08:13
【问题描述】:
我对 Angular 还是比较陌生,而且这种嵌套 JSON 的逻辑对我来说越来越好,所以我很抱歉。
我希望创建一个动态表单并使用this tutorial 作为起点。
我正在尝试构建仅在用户选择某个选项时才会显示的条件字段。我希望它能够工作,以便如果我的任何选项在数组中定义了子项,则会出现带有这些子项作为选项的后续输入。我还有很多事情要考虑,但现在我正在努力做到这一点,以便当用户选择选项 2 时,选项 2A 和选项 2B 会自动出现在下方的另一个下拉列表中。
如何创建一个 ngIf* 语句,说明“如果当前选择的选项有子选项,则将它们添加到另一个输入”?
我尝试检查“children”的数组长度是否大于零,还创建了一个名为“hasChildren”的布尔值并手动分配一个真/假值来检查(尽管我不喜欢这个解决方案,因为完成的应用程序将有许多嵌套选项,并且只检查数组是否为空会更容易)。
我也尝试了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
}
}
]
当用户选择“选项 2”时,我希望得到包含选项“选项 2A”和“选项 2B”的第二个下拉列表的输出,但我得到一个解析错误。
非常感谢!
【问题讨论】:
标签: javascript angular