0

(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>

这会引发错误:“无法读取未定义的属性 'title'”。我的服务按预期工作,就好像我删除了标题有效的 2 个按钮一样。一个正确方向的点会很棒。谢谢

4

1 回答 1

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>
于 2017-11-16T11:59:42.047 回答