Angular 2 : Can't bind to x since it isn't a known native property

标签 angular angular2-template

<分区>

在 Angular 2 组件中我有 authbox.component.ts

import {Component} from 'angular2/core';
import {COMMON_DIRECTIVES} from 'angular2/common';
import {Credentials} from './credentials'
@Component({
    selector: 'authbox',
    template: `<div>
       <div class="login-panel" *NgIf="!IsLogged">
            <input type="text" *NgModel="credentials.name" />
            <input type="password" *NgModel="credentials.password" />
            <button type="button" (click)="signIn(credentials)">→| Sign In</button>
        </div>
        <div class="logged-panel" *NgIf="IsLogged">
            <span>{nickname}</span>&nbsp;&nbsp; <button type="button" (click)="signOut()">|→ Sign out</button>
        </div>
    </div>`,
    directives: [COMMON_DIRECTIVES]
})


export class AuthBoxComponent {

    private _isLogged: boolean;

    get IsLogged(): boolean {
        return this._isLogged
    }
    set IsLogged(value: boolean) {
        this._isLogged = value;
    }

    public credentials: Credentials;

}

在浏览器中我得到错误«无法绑定(bind)到'NgModel',因为它不是已知的原生属性»和«无法绑定(bind)到'NgIf',因为它是'一个已知的本土属性(property)»。

我正在使用测试版 8。

最佳答案

一般来说,can't bind to xxx since it isn't a known native property当您在尝试使用属性指令或尝试设置属性绑定(bind)时在 HTML 中出现拼写错误时会发生错误。

常见的例子是当你错过了 *#let或使用 in而不是 of使用 Angular 内置结构指令:

<div  ngIf="..."                 // should be *ngIf
<div  ngFor="..."                // should be *ngFor="..."
<div *ngFor="let item in items"  // should be "let item of items"
<div *ngFor="item of items"      // should be "let item of items"

拼写错误或大小写错误也会产生问题::

<div *ngFer="..."
<div *NgFor="..."

另一个原因是,如果您指定了 DOM 元素或组件上不存在的属性:

<div [prop1]="..."       // prop1 isn't a valid DOM property for a div
<my-comp [answr]="..."   // typo, should be [answer]

对于内置 Angular 指令的拼写错误,由于拼写错误与任何内置指令选择器都不匹配,Angular 尝试设置一个绑定(bind)到 DOM 元素的属性(上面的 div示例)与拼写错误的名称。这失败了,因为 div没有原生 ngIfngFerprop1 DOM 属性。

--

对于属性(不是属性),您需要使用属性绑定(bind),例如 height svg 的属性: <svg [attr.height]="myHeightProp">

关于 Angular 2 : Can't bind to x since it isn't a known native property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35939950/

相关文章:

javascript - 在 Angular 6 中的初始组件之间共享服务 API 数据

angular - 在多个位置输出/渲染模板,与 ngIf 条件分开

angular - 无法分配给深层复制对象上的只读属性

node.js - Angular 2在不重新启动的情况下不显示图像

angular - Apollo:将查询中的某些过滤器的数据视为陈旧真实

angular - 尝试在我的自定义主题中导入 Angular Material 主题文件,但未找到该文件

angular - 将 null 设置为输入字段的空字符串值

angular - 如何检查无法读取未定义的属性 'testUndefined'

angular - 结合 [NgStyle] 与条件 (if.​​.else)

javascript - 带有 Bootstrap 4 Grid 的 Angular Material 2