* ngIf с универсальным строковым выражением, которое оценивает bool - PullRequest
0 голосов
/ 08 мая 2019

Привет. Я пытаюсь написать оператор * 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 содержит допустимое строковое выражение, которое будет возвращать либо true, либо false. Как я могу использовать этот hideExperssion в качестве параметра для *ngIf

Ответы [ 2 ]

0 голосов
/ 08 мая 2019

Вы не можете помещать выражения в строки, используйте метод для этого

<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;
   }
}
0 голосов
/ 08 мая 2019

Изменить на 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}`);
    }
}
...