【问题标题】:Can't bind to 'ngIf' since it isn't a known property of 'div' [duplicate]无法绑定到“ngIf”,因为它不是“div”的已知属性 [重复]
【发布时间】:2016-08-20 19:44:59
【问题描述】:

无法绑定到“ngIf”,因为它不是“div”的已知属性。

元素是<div [ngIf]="isAuth" id="sidebar">

组件是:

import SessionService from '../session/session.service';
import { Component } from '@angular/core';

@Component({
  providers: [],
  selector: 'navbar-left',
  styles: [require('./navbar-left.scss')],
  template: require('./navbar-left.html'),
})
export default class NavbarLeftComponent {
  public isAuth: boolean = false;

  constructor(private sessionService: SessionService) {
    this.isAuth = sessionService.sessionIsAuth();
  }
}

不确定我到底做错了什么?这是一个子组件。在父组件 aka App 组件中,ngIf 工作正常。 角RC5

【问题讨论】:

  • 确保您没有重复使用选择器名称,例如:selector: 'duplicatedNameHere,
  • 导入“CommonModule”,不要忘记执行两次“ng serve”来克服厄运......
  • 当我忘记将组件添加到模块的“声明”时出现此错误。
  • 声明的类似问题感谢@MichaelWyraz
  • 如果您在 jasmine 测试中遇到此类错误,请确保您已在声明中添加测试组件,例如 spec 文件中的“声明:[MyComponent]”。

标签: angular


【解决方案1】:

对于那些仍有问题的人,我也遇到了一个问题,我输入了ngif 而不是ngIf(注意大写的“I”)。

【讨论】:

  • nfIf 在我的情况下,有时... :facepalm:
  • 如果你写:*ngIf="{{condition}}"也可能发生。你不能写 {{ }}。 *ngIf="condition" 有效。
  • 是的,80% 的人在使用 *ngif ---> ngIf
  • ngIf 是一个不好的命名方式,它应该是 ngif ,但严格的命名标准强制命名为 ngIf 和 ngFor 而不是 ngfor 和 ngif
  • 我认为“指责骆驼案”并不准确。一个 5 年前的帖子有 400 次支持并不那么严重。我认为这只是表明人们不小心输入了错别字。当我意识到这不是因为我不知道如何使用 ngIf 时,这是因为一个错字。这里的大多数人都一样。
【解决方案2】:

如果您使用的是 RC5,请导入:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

并确保从提供组件的模块中导入 CommonModule

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

【讨论】:

  • 这个答案只有在我将export 添加到班级时才对我有效。
  • 别忘了“声明”
  • 如果在尝试了此页面中的所有建议后仍然出现错误,请尝试再次运行“ng serve”。
  • 确保模块也被导入到你的根目录app.module.ts
  • 确保有问题的子模块实际上是由父模块导入的。
【解决方案3】:

你应该像这样使用 *ngIf 而不是 [ngIf]:

<div *ngIf="isAuth" id="sidebar">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 2017-03-18
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 2020-10-24
    相关资源
    最近更新 更多