【问题标题】:Angular 4+ : Why isn't ng-if working in app.componet.html?Angular 4+:为什么 ngif 不能在 app.component.html 中工作?
【发布时间】:2018-04-16 20:42:23
【问题描述】:

我目前正尝试在我的 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 2+ 中,它是 *ngIf
  • 好的,很高兴知道,因为有很多不同的文档在流传。我应该提到,在我已经尝试过的许多事情中,*ng-if 就是其中之一。
  • 好的,所以问题不只是星号;我还需要删除连字符并将“i”大写。

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


【解决方案1】:

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

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

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

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

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

【讨论】:

    【解决方案2】:

    在应用组件中:

    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>
    

    【讨论】:

      猜你喜欢
      • 2020-08-09
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2019-09-16
      • 1970-01-01
      • 2018-09-08
      • 2019-01-31
      相关资源
      最近更新 更多