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

Angular 4+ : Why isn't ng-if working in app.componet.html?

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

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

在 Angular 中,结构指令以星号 (*) 为前缀,并且指令没有破折号。详情查看官方文档:

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

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

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

The asterisk is "syntactic sugar" for something a bit more complicated. Internally, Angular translates the *ngIf attribute into a element, wrapped around the host element.