【问题标题】:Angular 2 Component with ngModel not updating parent model具有ngModel的Angular 2组件未更新父模型
【发布时间】:2016-06-05 11:28:05
【问题描述】:

我正在尝试为复选框等输入创建一个包装器组件,但我无法更改父 (inputValue) 变量,即使它设置为 ngModel。

这是我的组件定义:

@Component({
selector: 'my-checkbox',
inputs: ['inputValue', 'label'],    
template: `
    <div class="ui checkbox">
      <input type="checkbox" name="example" [(ngModel)]="inputValue" (change)="onChange($event)">
      <label>{{label}}</label>
    </div>`
})

export class CheckboxComponent {    

inputValue: boolean;

onChange(event) {
    this.inputValue = event.currentTarget.checked;
    console.log(this.inputValue);
}}

我在父视图中这样使用它:

<my-checkbox [inputValue]="valueToUpdate" [label]="'Test Label'"></my-checkbox>

控制台确实记录正确,我可以看到内部 (inputValue) 正在更新,但外部“valueToUpdate”没有更新(ngModel 双向绑定未正确更新)。

【问题讨论】:

    标签: angularjs angular angular2-directives


    【解决方案1】:

    您需要为您的组件定义一个输出并使用EventEmitter 类来触发相应的事件。

    @Component({
      selector: 'my-checkbox',
      inputs: ['inputValue', 'label'],    
      outputs: ['inputValueChange']
      template: `
        <div class="ui checkbox">
          <input type="checkbox" name="example" [(ngModel)]="inputValue" (change)="onChange($event)">
          <label>{{label}}</label>
        </div>`
    })
    export class CheckboxComponent {    
    
      inputValue: boolean;
      inputValueChange: EventEmitter<any> = new EventEmitter();
    
      onChange(event) {
        this.inputValue = event.currentTarget.checked;
        console.log(this.inputValue);
        this.inputValueChange.emit(this.inputValue);
      }
    }
    

    这样你就可以为你的子组件使用两个绑定:

    <my-checkbox [(inputValue)]="valueToUpdate" [label]="'Test Label'">
    </my-checkbox>
    

    【讨论】:

    • 查看我的回答,了解一些改进建议。如果您喜欢它们,请随意将它们合并到您的答案中。
    • 好答案,谢谢!文档确实还需要改进!
    • 为了简洁起见,EventEmitter 需要声明一个类型,即:inputValueChange: EventEmitter&lt;any&gt; = new EventEmitter(); 否则 Typescript 会报错。
    • 是的,你是对的!没有这个,你会在编译过程中出错,但这并不妨碍执行代码;-) 谢谢你的评论!我相应地更新了我的答案......
    【解决方案2】:

    遵循@Thierry 的回答(即使用输出属性),但我建议使用内置的ngModelChange 事件,而不是使用两个事件绑定。即,拥有[(ngModel)](change) 会导致两个事件绑定,因此每次单击都会运行两个事件处理程序。内置的ngModelChange 事件也更好/更干净,因为$event 已经映射到复选框的值,而不是DOM 点击事件。因此,以下是对@Thierry 答案的建议更改:

    <input type="checkbox" name="example" 
      [ngModel]="inputValue" (ngModelChange)="onChange($event)">
    
    
    onChange(newValue) {
      this.inputValue = newValue;
      console.log(newValue);
      this.inputValueChange.emit(newValue);
    }
    

    Plunker

    【讨论】:

      猜你喜欢
      • 2016-05-21
      • 2016-12-30
      • 1970-01-01
      • 2016-12-10
      • 2017-12-26
      • 1970-01-01
      • 2017-07-25
      • 2020-05-18
      • 2016-07-08
      相关资源
      最近更新 更多