【问题标题】:Angular 2 Component with ngModel doesnt work带有 ngModel 的 Angular 2 组件不起作用
【发布时间】:2017-06-22 19:08:45
【问题描述】:

我是 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 的表单以进行 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>
`,

})

【问题讨论】:

标签: angular


【解决方案1】:

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

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

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

或添加standalone:true:

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

Plunker

【讨论】:

    【解决方案2】:

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

    希望这会有所帮助。

    【讨论】:

    • “不起作用”几乎是有帮助的。确切的行为是什么?您收到任何错误消息吗?
    猜你喜欢
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    相关资源
    最近更新 更多