Angular2 组件@Input 双向绑定 [英] Angular2 Component @Input two way binding

查看:28
本文介绍了Angular2 组件@Input 双向绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据驱动的 Angular 应用程序.我有一个切换组件,我以切换状态传递.我的问题是,除非我将切换布尔值作为对象传递,否则双向数据绑定似乎不起作用.有没有办法让它工作不使用 EventEmitter 或将变量作为对象传递.这是一个可重用的组件,并且应用程序是大量数据驱动的,因此将值作为对象而不是选项传递.我的代码是......

I have a data driven Angular application. I have a toggle component which I pass in a toggled state. My issue is that the two way data binding does not seem to work unless i pass in the toggle boolean as an object. Is there a way to get this to work without using an EventEmitter or passing the variable in as an object. This is to be a reusable component and the application is heavily data driven so passing the value in as an object in not an option. My code is....

toggle.html

toggle.html

<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>

toggle.component.ts

toggle.component.ts

import { Component, Input, EventEmitter, Output } from '@angular/core';

@Component({
  moduleId: module.id,
  selector: 'toggle-switch',
  templateUrl: 'toggle-switch.component.html',
  styleUrls: ['toggle-switch.component.css']
})

export class ToggleSwitchComponent {

  @Input() toggleId: string;
  @Input() toggled: boolean;

}

parent.component.html

parent.component.html

<toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch>

推荐答案

为了让 [(toggled)]="..." 工作,你需要

For [(toggled)]="..." to work you need

  @Input() toggled: boolean;
  @Output() toggledChange: EventEmitter<boolean> = new EventEmitter<boolean>();

  changeValue() {
    this.toggled = !(this.toggled); 
    this.toggledChange.emit(this.toggled);
  }

另请参阅双向绑定

[更新] - 2019 年 6 月 25 日
来自@Mitch 下面的评论:
值得注意的是,@Output 名称必须与 @Input 名称相同,但以 Change 结尾.您不能将其称为 onToggle 或其他名称.这是一个语法约定.

[UPDATE] - 25 June 2019
From @Mitch's comment below:
It's worth noting that the @Output name must be the same as the @Input name, but with Change on the end. You can't call it onToggle or something. It's a syntax convention.

这篇关于Angular2 组件@Input 双向绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆