【问题标题】:*ngIf to evaluate an updated variable*ngIf 评估更新的变量
【发布时间】:2018-04-29 23:01:24
【问题描述】:

(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 个按钮一样。朝着正确方向的一点会很棒。谢谢

【问题讨论】:

    标签: angular angular2-directives angular5


    【解决方案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>
    

    【讨论】:

    • 谢谢,这解决了问题。虽然提出了一个新的。我的 routerLink 需要再次单击才能更改按钮。应坚持找出原因;)。欢呼
    猜你喜欢
    • 2016-10-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-08
    • 1970-01-01
    相关资源
    最近更新 更多