首页 文章

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

提问于
浏览
0

帮助修复条件以显示数据 . 我通过异步服务得到M的模型,所以我使用> model?.something <notation来避免错误,当模型仍未定义时 . 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 回答

  • 1

    请试试:

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

相关问题