【问题标题】:Angular4, can't hide contentAngular4,无法隐藏内容
【发布时间】:2017-09-12 12:00:26
【问题描述】:

我在 Angular 4 框架中有一个组件,看起来像这样

import { ListService } from '../list/list.service';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'view',
  template: `
  <div *ngIf="row?.id">
    <div>
      <p>{{row.id}}</p>
      <p>{{row.name}}</p>
      <p>{{row.weight}}</p>
      <p>{{row.symbol}}</p>
    </div>
  </div>
  <div *ngIf="!row">test</div> 
  <router-outlet></router-outlet>
  `,
  styles: []
})
export class ViewComponent implements OnInit {

  constructor(private route: ActivatedRoute,
    private service: ListService) {
    this.route.params.subscribe(params => {
      const id = parseInt(params['id']);
      if (id) {
        this.row = this.service.getRow(id);
        console.log(this);
      }
    });
  }

  row;

  ngOnInit() { }
  showInfo(){
      console.log(this)
  }
}

虽然第一个 *ngIf="row?.id" 工作正常,第二个表现奇怪的意思总是true,我做错了什么吗?

编辑:

当我测试它时,似乎 ViewComponent 没有正确更新,这意味着当我在 constructor &gt; after if condition 内执行 console.log 时,Viewcomponent 有 3 个属性 routeservicerow 但是当我创建函数时

showInfo(){
    console.log(this)
}

现在this -> ViewComponent 只有两个属性routeservice

这可能是范围的问题吗?

【问题讨论】:

  • 你认为它什么时候是假的?
  • 我预计当没有人点击任何行时它会是错误的

标签: javascript angular angular2-template angular2-components


【解决方案1】:

您应该使用以下内容

<div *ngIf="row === undefined">test</div>

*ngIf="!row" 正在检查 row === false

【讨论】:

  • !row 不等同于row === false,而是等同于row == false
【解决方案2】:

*ngIf="!row" 检查该行是否为假值(表示row == false,这反过来又可能意味着,如果行是一个对象,则该行是nullundefined)。

只要您的行不为空或未定义,此条件将为真,并且会出现“测试”。

如果您想对第一个 *ngIf 进行相反的检查,只需完全否定它:

<div *ngIf="!(row?.id)">test</div> 

(括号只是为了清楚)

【讨论】:

    猜你喜欢
    • 2018-06-16
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    相关资源
    最近更新 更多