Angular 2:无法绑定到x,因为它不是已知的本机属性

Arm*_*ots 52 angular2-template angular

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

}
Run Code Online (Sandbox Code Playgroud)

在浏览器中我遇到错误« 无法绑定到'NgModel',因为它不是已知的本机属性 »和« 无法绑定到'NgIf',因为它不是已知的本机属性 ».

我正在使用beta 8.

Mar*_*cok 44

通常,can't bind to xxx since it isn't a known native property当您在尝试使用属性指令或尝试设置属性绑定时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"
Run Code Online (Sandbox Code Playgroud)

拼写错误或错误的情况也会产生问题::

<div *ngFer="..."
<div *NgFor="..."
Run Code Online (Sandbox Code Playgroud)

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

<div [prop1]="..."       // prop1 isn't a valid DOM property for a div
<my-comp [answr]="..."   // typo, should be [answer]
Run Code Online (Sandbox Code Playgroud)

对于具有内置Angular指令的拼写错误,由于拼写错误与任何内置指令选择器都不匹配,因此Angular尝试div使用拼写错误名称设置绑定到DOM元素的属性(在上面的示例中) .这将失败,因为div没有本地ngIfngFerprop1DOM属性.

-

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

  • 我遇到了这个错误,因为我忘了将指令添加到组件的组件声明中的指令数组中. (6认同)
  • 我不知道任何这样的列表,特别是考虑到,例如,([根据MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element))DOM元素继承来自Node和EventTarget,并实现ParentNode,ChildNode,NonDocumentTypeChildNode和Animatable.每个都可以拥有自己的属性.要查找属性,我通常使用MDN或使用Chrome开发工具(元素,然后是属性选项卡).在你的情况下,`height`是svg元素的属性,而不是属性,所以你需要使用属性绑定:`<svg [attr.height] ="myHeightProp">`. (2认同)

mic*_*yks 18

尝试使用[(ngModel)],而不是*NgModel*ngIf代替*NgIf

<span>{{nickname}}</span>&nbsp;&nbsp; <button type="button" (click)="signOut()">|? Sign out</button>

export class AuthBoxComponent {
    nickname="guest";
    ...
}
Run Code Online (Sandbox Code Playgroud)