【发布时间】: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