如何在 angular 4 中以动态形式设置 ngIf 动态条件

How to set ngIf dynamic condition in dynamic form in angular 4

我正在创建一个动态表单,其中我根据 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"'
      })

visibility: 'this.form.get("firstName").value ==="abc"',如您所见,您应该像往常一样在组件 class 逻辑中写入 json,因为它会 运行 在组件上下文

CODE EXAMPLE