* ngIf评估更新的变量

时间:2017-11-16 11:58:38

标签: angular angular2-directives angular5

(Angular / JS学习者)我有一个对象,通过服务更新值,具体取决于当前哪个子控制器处于活动状态。我试图根据这个对象值来显示一个不同的按钮。

我的父控制器如下:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ChildDataService } from "../core/helpers/child-data.service";
import { Subscription } from "rxjs/Subscription";

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
  childDetails: {title?: string};

  private subscription:Subscription;

  constructor( private childDataService: ChildDataService) {
    this.childDataService.childLoaded$.subscribe(
      newChildDetails => {
        console.log(newChildDetails);
        this.childDetails = newChildDetails
      });
  }
  someFunction(){};

  someFunction2(){};
}

我父母HTML的相关部分看起来像:

<div class="subheader">
  <h1>{{ childDetails.title }}</h1>
  <button *ngIf="childDetails.title == 'dashboard'" (click)="someFunction()">dashboard</button>
  <button *ngIf="childDetails.title == 'page2'" (click)="someFunction2()">page2</button>
</div>

这会引发错误:&#34;无法读取属性&#39;标题&#39;未定义&#34;。我的服务正在按预期工作,就好像我删除标题的2个按钮一样。正确方向上的一点很棒。感谢

1 个答案:

答案 0 :(得分:1)

使用安全导航操作员

<div class="subheader">
  <h1>{{ childDetails?.title }}</h1>
  <button *ngIf="childDetails?.title == 'dashboard'" (click)="someFunction()">dashboard</button>
  <button *ngIf="childDetails?.title == 'page2'" (click)="someFunction2()">page2</button>
</div>