【问题标题】:2 way data binding didn't works in angular 22 方式数据绑定在角度 2 中不起作用
【发布时间】:2017-06-16 06:05:59
【问题描述】:

在我的 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() { }

【问题讨论】:

  • 因为家未定义
  • constructor(){} 必须在类内 EventComponent
  • @Ajith V Manali 什么错误?

标签: angular typescript data-binding


【解决方案1】:

像这样在构造函数中初始化类变量总是个好主意

export class EventComponent {
   home:Home = null; // or home:Home; 
   constructor() { 
        this.home = new Home()
    }
}

【讨论】:

    【解决方案2】:

    应该只是aboutus

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        由于home 未初始化,这就是home.aboutus 未与html 模板绑定的原因。

        试试下面的代码

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

        【讨论】:

          【解决方案5】:

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

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-06
            • 1970-01-01
            • 2019-01-01
            • 2017-10-18
            • 2018-10-03
            • 2018-12-25
            • 2015-09-05
            • 2023-03-25
            相关资源
            最近更新 更多