Angular 4,使用ngIf进行条件显示

时间:2017-11-24 10:11:23

标签: angular angular-ng-if

帮助修复条件以显示数据。 我通过异步服务得到M的模型,所以我使用> model?.something<模型尚未定义时避免错误的符号。 title为null或'somestring'。 表达有问题。无论我选择什么形式,它总是显示一个案例。 我早期避免使用此类型表达式,无法正确转换为打字稿。

import { Component } from '@angular/core';
import { M } from './model';

@Component({
  selector: 'app-test',
  template: `
<p *ngIf="model1?.title !== null">
  Display text if title exist('common string')
</p>
<p *ngIf="model2?.title === null">
  Display text if title equal to null
</p>
  `,
  styleUrls: ['./test.component.css']
})

export class TestComponent {
  model1: M;
  model2: M;
  constructor() {
    this.model1 = {
      title: 'username'
    };
    this.model2 = {
      title: null
    };
  }
}

export class M {
    public title: string;

    public constructor(){}
}

1 个答案:

答案 0 :(得分:1)

请尝试:

<h1 *ngIf="model1.title!==null">
    OK
  </h1>

   <h1 *ngIf="model2.title!==null">
    OK
  </h1>
相关问题