[英]How to set ngIf dynamic condition in dynamic form in angular 4
I am creating a dynamic form where I am populating the fields dynamically based on the response from JSON like. 我正在创建一个动态表单,在该表单中,我根据JSON之类的响应动态填充字段。
Eg:- 例如:-
[{
"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"
}]
I have a usecase where the second field should be visible only when the first field should have the values 'abc' or 'xyz'(Condition is written in the JSON property).How can that be achieved dynamically? 我有一个用例,只有当第一个字段的值必须为``abc''或``xyz''(条件写在JSON属性中)时,第二个字段才可见。如何动态实现?
Create evaluation
method in component: 在组件中创建evaluation
方法:
isVisible(value){
//console.log(eval(value));
return eval(value);
}
And call it in template like this: 并在这样的模板中调用它:
<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>
Your json
file will be like: 您的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"'
})
visibility: 'this.form.get("firstName").value ==="abc"'
, as you can see you should write in json
as usual in component class logic, because it will run in component context visibility: 'this.form.get("firstName").value ==="abc"'
,如您所见,您应该像往常一样在组件类逻辑中以json
编写,因为它将在组件上下文中运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.