使用ngModel的Angular 2组件不起作用

时间:2017-02-05 21:43:14

标签: angular

Iam在Angular 2中的新内容,在发布之前我试图通过互联网搜索解决方案,但我无法获得解决方案。如果有人能帮助我,我将感激不尽

我的代码可以在没有ngModel的情况下使用

user.component

import { Component } from '@angular/core';

@Component({
selector: 'user',
template: `<h3>Welcome {{name}}</h3>
 <p>EMAIL: {{email}}</p>
 <div *ngIf="showHobbies"> 
 <p>HOBBIES:</p>  
    <ul>
      <li *ngFor="let hobby of hobbies">
         {{hobby}}
      </li>
     </ul>
 </div>
`,
})

export class UsersComponent  {

username:string;
private name:string;
private email:string;
private hobbies:string[];
private showHobbies:boolean;

constructor(){
    this.username="";
    this.showHobbies=false;
    this.name="My name";
    this.email="My Email";
    this.hobbies=['swimming','watching movie','playing football'];
}

toggleHobbies(){
     if(this.showHobbies==true){
         this.showHobbies = false;
     }
     else {
         this.showHobbies = true;
     }
}

}

app.module看起来像这样

import { NgModule }      from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';
import { UsersComponent  }  from './components/users.component';

@NgModule({
  imports:      [ BrowserModule,FormsModule],
  declarations: [ AppComponent,UsersComponent],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }

我的app.component看起来像这样

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<user></user>`,
})

export class AppComponent  { }

上面的代码在user.component中使用ngModule for 2way绑定添加表单时停止工作

@Component({
    selector: 'user',
    template: `<h3>Welcome {{name}}</h3>
     <p>EMAIL: {{email}}</p>
     <p>TEL: {{telephone}}</p>
     <button (click)="toggleHobbies()">{{ showHobbies ? 'Hide hobbies' : 'Show hobbies'}}</button>

    <div *ngIf="showHobbies"> 
     <p>HOBBIES:</p>  
        <ul>
           <li *ngFor="let hobby of hobbies">
              {{hobby}}
           </li>
        </ul>
     </div>

当我添加下面的表单时,其他代码停止工作

<form>
   <label>Name</label> <br/>
   <input type="text" [(ngModel)]="username" />
   <p>Hello {{username}} </p>
</form>
`,

})

2 个答案:

答案 0 :(得分:2)

我建议您查看开发人员工具,在这种情况下,您会得到一个非常明确的解释错误,实际上告诉您错误的确切位置:

ErrorMessage

所以这可以通过两种方式解决。添加name属性:

<input type="text" name="username" [(ngModel)]="username" />

或添加standalone:true

<input type="text" [(ngModel)]="username" [ngModelOptions]="{standalone: true}" />

<强> Plunker

答案 1 :(得分:1)

我认为您收到模板解析错误,因为您的UsersComponent中没有username变量。

希望这会有所帮助。