Angular2 Component @ Entering two-way binding

I have an application with an Angular data drive. I have a switch component that I pass to switch. My problem is that two-way data binding does not work unless I go to toggle boolean as an object. Is there a way to get this to work without using an EventEmitter or passing a variable as an object . This should be a reusable component, and the application is heavily data driven, so passing the value as an object is not an option. My code ...

toggle.html

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

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

 <toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch> 
+37
source share
2 answers

To work [(toggled)]="..." you need

  @Input() toggled: boolean; @Output() toggledChange: EventEmitter<boolean> = new EventEmitter<boolean>(); changeValue() { this.toggled = !(this.toggled); this.toggledChange.emit(this.toggled); } 

See also Bilateral binding

[UPDATE] - June 25, 2019
From @Mitch's comment below:
It is worth noting that the name @Output should match the name @Input , but with Change at the end. You cannot call it onToggle or anything else. This is a syntax convention.

+68
source

Although this issue has been over 2 years old, I want to pay my 5 cents ...

This is not an Angular problem, but how Javascript works ... Simple variables (number, string, boolean, etc.) are passed by value, while complex (objects, arrays) are passed by reference:

You can read more about this in the Kyle Simpson series. You do not know js:

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

That way, you can use the @Input () object variable to divide the scope between components without the need for emitters, observers, and the like.

 // 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"/> 

Thus, you can change all the properties of the object and get the same value in both components, because they have the same link.

0
source

Source: https://habr.com/ru/post/1014652/


All Articles