如何在角度4中以动态形式设置ngIf动态条件 [英] How to set ngIf dynamic condition in dynamic form in angular 4

查看:206
本文介绍了如何在角度4中以动态形式设置ngIf动态条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个动态表单,在该表单中,我根据JSON之类的响应动态填充字段.

I am creating a dynamic form where I am populating the fields dynamically based on the response from JSON like.

例如:-

[{
  "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属性中)时,第二个字段才可见.如何动态实现?

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?

推荐答案

在组件中创建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>

您的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"',如您所见,您应该像往常一样在组件类逻辑中用json编写,因为它将在组件上下文中运行

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

代码示例

这篇关于如何在角度4中以动态形式设置ngIf动态条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆