无法绑定到“ng-forOf",因为它不是已知的本机属性 [英] Can't bind to 'ng-forOf' since it isn't a known native property

查看:28
本文介绍了无法绑定到“ng-forOf",因为它不是已知的本机属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照此处的基本 Angular 2 教程进行操作:

I am trying to follow the basic Angular 2 tutorial here:

https://angular.io/docs/js/latest/指南/显示数据.html

我可以使用以下代码让 Angular 应用加载并显示我的名字:

I can get the angular app to load and display my name with this code:

import { Component, View, bootstrap } from 'angular2/angular2';

@Component({
    selector: "my-app"
})

class AppComponent {
    myName: string;
    names: Array<string>;
    constructor() {
        this.myName = "Neil";

    }

}
bootstrap(AppComponent);

但是,当我尝试添加一个字符串数组并尝试使用 ng-for 显示它们时,它会引发以下错误:

However when I try to add an array of strings and try to display them with an ng-for, it is throwing the following error:

Can't bind to 'ng-forOf' since it isn't a known native property ("
    <p>Friends:</p>
    <ul>
        <li [ERROR ->]*ng-for="#name of names">
        {{ name }}
        </li>
"): AppComponent@4:16
Property binding ng-forOf not used by any directive on an embedded template ("
    <p>Friends:</p>
    <ul>
        [ERROR ->]<li *ng-for="#name of names">
        {{ name }}
        </li>
"): AppComponent@4:12

代码如下:

import { Component, View, bootstrap } from 'angular2/angular2';

@Component({
    selector: "my-app"
})

@View({
    template: `
        <p>My name: {{ myName }}</p>
        <p>Friends:</p>
        <ul>
            <li *ng-for="#name of names">
                {{ name }}
            </li>
        </ul>
    `,
    directives: [ NgFor ]
})

class AppComponent {
    myName: string;
    names: Array<string>;
    constructor() {
        this.myName = "Neil";
        this.names = ["Tom", "Dick", "Harry"];
    }

}
bootstrap(AppComponent);

我错过了什么?

推荐答案

如果您使用 alpha 52,请查看 GitHub 存储库中的 CHANGELOG.md.他们将模板更改为区分大小写,即 ngFor 而不是 ng-for(类似于所有其他指令)

If you use alpha 52, check out the CHANGELOG.md in the GitHub repo. They changed the template to case-sensitive which is ngFor instead of ng-for (similar for all other directives)

诸如 之类的元素名称并未更改,以保持与自定义元素规范兼容,后者需要在自定义元素的标签名称中使用破折号.

Element names like <router-outlet> weren't changed though to stay compatible with custom elements spec which requires a dash in the tag name of custom elements.

>= RC.5(和最终版) ngFor 和类似的指令在默认情况下不是环境的.它们需要像

In >= RC.5 (and final) ngFor and similar directives are not ambient by default. They need to be provided explicitly like

@NgModule({
  imports: [CommonModule],

或者如果您不介意模块被锁定为仅限浏览器

or if you don't mind the module being locked to be browser-only

@NgModule({
  imports: [BrowserModule],

BrowserModule导出 CommonModule 也像 WorkerAppModule 确实如此.

更新

BrowserModule 应该在应用模块中导入,在其他模块中 CommonModule 应该被导入.

The BrowserModule should be imported in the app module, in other modules CommonModule should be imported instead.

这篇关于无法绑定到“ng-forOf",因为它不是已知的本机属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆