Angular 4+:为什么不是ng-if在app.componet.html中工作?

时间:2018-04-16 20:42:24

标签: angular angular-ng-if ngif angularjs-ng-if

我目前正在尝试在app.component.html文件中使用ng-if指令:

<p>This should appear.</p>

<p ng-if="0==1">This shouldn't, but it does.</p>

我的app.component.ts文件如下所示:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
}

我尝试了许多不同的值而不是0==1,但它仍然不起作用,包括使用传入变量的值。它正在编译和显示而没有错误,但没有删除第二个p

我也试过*ng-if。当我这样做时,我收到一个错误:

Template parse errors:

Can't bind to 'ng-if' since it isn't a known property of 'p'. ("<p>This should appear.</p>

<p [ERROR ->]*ng-if="0==1">This shouldn't, but it does.</p>

"): ng:///AppModule/AppComponent.html@2:3
Property binding ng-if not used by any directive on an embedded template. 
Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations". ("<p>This should appear.</p>

2 个答案:

答案 0 :(得分:0)

在Appcomponent中:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
isShowing = true;
}

在你的标记中:

<p *ngIf="isShowing">This shouldn't, but it does.</p>

答案 1 :(得分:0)

在Angular结构指令中以星号(*)为前缀,指令不带破折号。有关详细信息,请查看官方文档:

修复代码写入*ngIf而不是ng-if

https://angular.io/guide/structural-directives#asterisk

从官方文档中快速了解原因:

  

星号是“语法糖”,有点复杂。在内部,Angular将* ngIf属性转换为包含主机元素的元素。