Angular2 two-way data binding

前端 未结 8 1823
谎友^
谎友^ 2020-12-15 05:10

I know Angular2 doesn\'t have two-way data binding but is there a way to mimick the two-way data binding behavior from Angular1.x?

8条回答
  •  失恋的感觉
    2020-12-15 05:37

    Yes there is two-way binding in angular2. See here: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel

    So, how to use it in custom components?

    What I like to do is something this:

    private currentSelectedItem: MachineItem;
    @Output() selectedItemChange: EventEmitter = new EventEmitter();
    
    @Input() set selectedItem(machineItem: MachineItem) {
        this.currentSelectedItem = machineItem;
        this.selectedItemChange.emit(machineItem); 
    }
    
    get selectedItem(): MachineItem {
        return this.currentSelectedItem; 
    }
    

    And use it like

    
    

    You can also emit the new value where it is actually changed. But I find it quite convenient to do that gloabaly in a setter method and don't have to bother e.g. when I bind it directly to my view.

提交回复
热议问题