-3

我目前正在尝试在我的 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>
4

2 回答 2

0

在 App 组件中:

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>
于 2018-04-16T21:02:36.603 回答
0

在 Angular 中,结构指令以星号 (*) 为前缀,并且指令的书写方式不带破折号。详情查看官方文档:

要修复您的代码编写*ngIf而不是ng-if.

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

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

星号是更复杂的东西的“语法糖”。在内部,Angular 将 *ngIf 属性转换为一个元素,包裹在宿主元素周围。

于 2018-04-16T21:03:31.867 回答