【问题标题】:Angular2 Two way bindings doesn't work on FirefoxAngular2双向绑定在Firefox上不起作用
【发布时间】:2016-04-15 14:59:11
【问题描述】:

我是使用 Angular 2 的新手。我使用 Typesript 开发了一些表单,它适用于 Chrome,但不适用于 FireFox(版本 45)。 首先,我尝试了两种浏览器的“双向”数据绑定:Chrome 具有正确的行为,但 FireFox 没有考虑与 ngModel 的绑定(根据 angular2 的 5 分钟快速入门查找我的示例)。

此外,bootstrap 的日期选择器在 Chrome 上运行良好,在 Firefox 上运行不佳。

提前致谢,

app.component.ts

import {Component, OnInit, Event} from 'angular2/core';
import {FORM_DIRECTIVES, NgForm, NgIf, NgFor} from 'angular2/common';


import {Types} from './types';

@Component({
    selector: 'my-app',
    templateUrl:'./app/app.component.html',
    directives : [
      FORM_DIRECTIVES,
      NgForm,
      NgIf,
      NgFor
    ]
})
export class AppComponent implements OnInit {

  field:any;

  types:Array<string> = Types;

  ngOnInit() {
      this.field= {};
  }

  onChange(event:Event) {
    console.log(this.field.type);
  }
}

app.component.html

<h1>My First Angular 2 App</h1>

<div class="form-group">
<label class="col-sm-2 control-label"> Select </label>
<div class="col-sm-4">

<select class="form-control"
        [(ngModel)]="field.type"
        (change)=onChange($event)
        title="Type">
   <option *ngFor="#t of types">{{ t }}</option>
</select>
</div>

<hr/>

<label class="col-sm-2 control-label"> Input </label>
<div class="col-sm-4">
  <input type="text"
        class="form-control input-sm"
        [(ngModel)]="field.type"
        placeholder="type">
</div>
</div>

【问题讨论】:

  • 你不需要这些`directives : [ FORM_DIRECTIVES, NgForm, NgIf, NgFor ],它们是默认提供的。
  • 浏览器控制台是否出现错误?尝试将field:any; 更改为field:any = {}; 无需等到ngOnInit() 进行初始化。
  • 控制台没有错误!
  • 对我来说同样的问题,但反过来:在 FF 中可以正常工作,而不是在 Chrome 中。

标签: firefox angular compatibility 2-way-object-databinding


【解决方案1】:

我找到了一个不是很好的解决方案:

  • HTML 文件:在我添加的选择标签中#typeField
  • TS 文件:我更改了 onChange 方法,如下所示:

app.component.ts

import {Component} from 'angular2/core';


import {Types} from './types';

@Component({
    selector: 'my-app',
    templateUrl:'./app/app.component.html'
})

export class AppComponent {

  field:any = {};

  types:Array<string> = Types;

  onChange(event:Event, newValue:any) {
    this.field.type = newValue;
    console.log(this.field.type);
  }
}

app.component.html

<h1>My First Angular 2 App</h1>

<div class="form-group">
<label class="col-sm-2 control-label"> Select </label>
<div class="col-sm-4">

<select class="form-control"
        [(ngModel)]="field.type"
        #typeField
        (change)="onChange($event, typeField.value)"
        title="Type">
   <option *ngFor="#t of types">{{ t }}</option>
</select>
</div>

<hr/>

<label class="col-sm-2 control-label"> Input </label>
<div class="col-sm-4">
  <input type="text"
        class="form-control input-sm"
        [(ngModel)]="field.type"
        placeholder="type">
</div>
</div>

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 2019-11-13
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 2011-10-14
    相关资源
    最近更新 更多