Angular 4+ : 为什么 ng-if 在 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>

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

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

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

从官方文档中快速浏览原因:

星号是"句法糖",表示更复杂的东西。在内部,Angular 将 *ngIf 属性转换为一个元素,环绕在主机元素周围。

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

最新更新