2路数据绑定在角度2中不起作用

时间:2017-06-16 06:06:00

标签: angular typescript data-binding

在我的angular 2应用程序中,我尝试使用ngmodel绑定视图数据,但它没有像我预期的那样工作。

event.component.html

 <div  class="form-group">
     <label for="comment">About Us:</label>
         <input type="text" name="aboutus" class="form-control" 
 [(ngModel)]="home.aboutus" required placeholder="aboutus"/>{{home.aboutus}}

 </div>

homemenu.ts

  export class Home {
  aboutus: string;
    }

eventcomponent.ts      export class EventComponent { home:Home; } constructor() { }

5 个答案:

答案 0 :(得分:1)

应该只是 aboutus

  <input type="text" name="aboutus" class="form-control" 
 [(ngModel)]="aboutus" required placeholder="aboutus"/>{{aboutus}}

答案 1 :(得分:1)

您需要在事件component.ts中初始化home:

export class EventComponent {
       home:Home = new Home(); 
       constructor() { }
   }

答案 2 :(得分:1)

由于home未初始化,因此home.aboutus未与html模板绑定。

尝试以下代码

export class EventComponent {
    home:Home;

    constructor() {
        this.home = new Home();
    }

}

答案 3 :(得分:1)

在像

这样的构造函数中初始化类变量总是好主意
export class EventComponent {
   home:Home = null; // or home:Home; 
   constructor() { 
        this.home = new Home()
    }
}

答案 4 :(得分:0)

绑定home实例属性而绑定[(ngModel)] =“home.aboutus”使用字符串插值{{home.aboutus}}吐出输入的值。

export class EventComponent{
      home: Home;
      constructor() {
        this.home = new Home();
      }
}
相关问题