【问题标题】:*ngIf with generic string expression that evaluates bool*ngIf 带有计算布尔值的通用字符串表达式
【发布时间】:2019-05-08 06:48:40
【问题描述】:

您好,我正在尝试编写 *ngIf 语句,该语句将通用字符串作为输入,然后返回 true/false 例如

以下是示例组件 html 和 ts 文件。

   <div>
      <p *ngIf='hideExpression'>
        This will be visible only if employee member is employee.
      </p>
   </div>

users.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {

  hideExpression = '';
  isEmployee = false;
  constructor() { }

  ngOnInit() {
    //Note:  I am going to fetch this expression from Database which is stored in string form
    this.hideExpression = 'isEmployee === true';
  }
}

我的成员变量hideExpression 包含一个有效的字符串表达式,它将返回真或假。我怎样才能使用这个hideExperssion作为*ngIf的参数

【问题讨论】:

  • 你不能。不要将代码放在字符串中。将代码放入函数中。只需将 hideExpression 设为函数或方法即可。
  • eval() 函数能帮到你吗?
  • @PareshGami,非常好。它按预期工作,但看起来打字稿对它不满意。 TypeScript 具有名为“no-eval”的内置规则。我们可以忽略并继续前进,但必须有更好的方法来解决这个问题。
  • 你可以忽略规则 // tslint:disable-next-line:no-eval :P

标签: angular typescript angular-template


【解决方案1】:

您不能将表达式放在字符串中,为此使用方法

<div>
      <p *ngIf='isEmployee'>
        This will be visible only if employee member is employee.
      </p>
   </div>



import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css']
})
export class UsersComponent implements OnInit {


  isEmployee = false;
  constructor() { }
       hideExpression();
  ngOnInit() {

  }
   private hideExpression(){
     return !this.isEmployee;
   }
}

【讨论】:

  • 谢谢。我想实现通用框架,我打算从数据库中获取 hideExpression。我已经更新了我原来的问题。
【解决方案2】:

更改为this.hideExpression = this.isEmployee === true;

ngOnInit() {
    this.hideExpression = this.isEmployee === true;
}

更新

如果你想从数据库中获取 hideExpression,你需要像这样创建一个服务并从数据库中获取数据

constructor(private yourService: EmployeeService) {
}

ngOnInit() {
    this.yourService.getEmployee(id).subscribe(data=>{
            this.hideExpression = data.isEmployee === true;
    });
}

@Injectable()
export class EmployeeService {
    constructor(private http: HttpClient){
    }

    getEmployee(id){
        return this.http.get(`/api/employee?id=${id}`);
    }
}

【讨论】:

  • 这只会在组件初始化时计算一次表达式。
  • 想法是,我想实现通用框架,我打算从数据库中获取 hideExpression。
猜你喜欢
  • 2013-04-15
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多