Angular2 Component @Input two way binding

后端 未结 2 1319
攒了一身酷
攒了一身酷 2021-01-30 19:40

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 p

相关标签:
2条回答
  • 2021-01-30 20:16

    Although the question has more than 2 years old I want to contribute my 5 cents...

    It isn't a problem about Angular, its about how Javascript works... Simple variables (number, string, boolean, etc) are passed by value whereas complex ones (objects, arrays) are passed by reference:

    You can read more about this in Kyle Simpson´s series You dont know js:

    https://github.com/getify/You-Dont-Know-JS/blob/master/types%20%26%20grammar/ch2.md#value-vs-reference

    So, you can use an @Input() object variable to share scope between components without need to use emitters, observers and whatever similar.

    // In toggle component you define your Input as an config object
    @Input() vm: Object = {};
    
    // In the Component that uses toggle componet you pass an object where you define all needed needed variables as properties from that object:
    config: Object = {
        model: 'whateverValue',
        id: 'whateverId'
    };
    
    <input type="checkbox" [vm]="config" name="check"/>
    

    This way you can modify all object properties and you get same value in both components because they share same reference.

    0 讨论(0)
  • 2021-01-30 20:21

    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);
      }
    

    See also Two-way binding

    [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.

    0 讨论(0)
提交回复
热议问题