@Input: Two-way data binding does not work

I am trying to reproduce this: http://plnkr.co/edit/OB2YTMJyeY3h9FOaztak?p=preview (this plunker is an example that works, and I want to get the same result but with my code that does not work)

==================================================== =================

I have this simple two-way binding, I am trying to update a string property, such as on the parent, as on the child

Problem: when you click " update from parent ", both updates are bindings. But when you click " update from child " only the child elements are updated!

It seems very simple, what can I do wrong?

(Note: I used the angular CLI to run the project)

==================================================== =================

Parent component:

import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-my-dad', templateUrl: './my-dad.component.html', styleUrls: ['./my-dad.component.css'] }) export class MyDadComponent { parentModel: string; constructor() {} updateModel(){ this.parentModel += ' parent'; } } 

Parent template

 <h2>Parent: {{ parentModel }} </h2> <button (click)="updateModel()"> update from parent </button> <app-my-child [(model)]="parentModel"></app-my-child> 

Child component

 import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-my-child', templateUrl: './my-child.component.html', styleUrls: ['./my-child.component.css'] }) export class MyChildComponent { @Input() model: string; constructor() { } updateModel(){ this.model += ' child'; } } 

Children's template:

 <h2>Child: {{ model }} </h2> <button (click)="updateModel()"> update from child </button> 
+5
source share
1 answer

For two-way binding using the syntax [(xxx)] (banana in a box) you need both @Input() and @Output() with the corresponding names, for example

 @Input() myProp:String; @Output() myPropChange:EventEmitter<String> = new EventEmitter<String>; 

See also https://angular.io/docs/dart/latest/guide/template-syntax.html#!#two-way

For two-way binding with ngModel to work, your component must implement ControlValueAccessor

see also

+6
source

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


All Articles