gpt4 book ai didi

javascript - 如何以 Angular 4的动态形式设置ngIf动态条件

转载 作者:行者123 更新时间:2023-11-30 14:41:47 25 4
gpt4 key购买 nike

我正在创建一个动态表单,我在其中根据来自 JSON 的响应动态填充字段。

例如:-

[{
"type":"text",
"required":true,
"minlength": 3,
"maxlength":5,
"name":"fname",
"visibility":true
},
{
"type":"text",
"required":true,
"minlength": 3,
"maxlength":5,
"name":"lname",
"visibility":"fname == 'abc' || fname == 'xyz'"
},
{
"type":"text",
"required":true,
"minlength": 3,
"maxlength":5,
"name":"fid",
"visibility":true
},
{
"type":"text",
"required":true,
"minlength": 3,
"maxlength":5,
"name":"lid",
"visibility":"fid == 1 || fid == 4"
}]

我有一个用例,其中仅当第一个字段的值应为“abc”或“xyz”(条件写入 JSON 属性中)时,第二个字段才应可见。如何动态实现?

最佳答案

在组件中创建evaluation方法:

 isVisible(value){
//console.log(eval(value));
return eval(value);
}

然后像这样在模板中调用它:

<div *ngIf="isVisible(question.visibility)">
<label [attr.for]="question.key">{{question.label}}</label>
<div [ngSwitch]="question.controlType">
<input [name]="question.key" *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type">

<select [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
<option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
</select>
</div>
<div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>

您的 json 文件将如下所示:

 ...
new TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1,
visibility: 'true'
}),

new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2,
visibility: 'this.form.get("firstName").value ==="abc"'
})

可见性:'this.form.get("firstName").value ==="abc"',如您所见,您应该在 json 中编写为通常在组件类逻辑中,因为它将在组件上下文中运行

CODE EXAMPLE

关于javascript - 如何以 Angular 4的动态形式设置ngIf动态条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com