首页 文章

Angular 2:可以't bind to x since it isn' t一个已知的原生属性[重复]

提问于
浏览
51

这个问题在这里已有答案:

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

}

在浏览器中我遇到了错误«可以't bind to ' NgModel ' since it isn' t一个已知的本机属性»和«可以't bind to ' NgIf ' since it isn' t一个已知的本机属性» .

我正在使用beta 8 .

2 回答

  • 18

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

    <span>{{nickname}}</span>&nbsp;&nbsp; <button type="button" (click)="signOut()">|→ Sign out</button>
    
    export class AuthBoxComponent {
        nickname="guest";
        ...
    }
    
  • 43

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

    常见示例是当您错过 *#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会尝试使用拼写错误设置绑定到DOM元素的属性(上例中的 div )名称 . 这会失败,因为 div 没有本机 ngIfngFerprop1 DOM属性 .

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

相关问题