1

How to make 2-way data binding for a custom input in child component in Angular 8?

I used banana-in-a-box [(...)] syntax but it doesn't make changes in child component visible in the parent component.

In the result, it should work with the banana-in-a-box syntax.

parent.component.ts

...
public childVisibility: boolean = true;
...

parent.component.html

childVisibility : {{childVisibility}}

<app-child-component [(visible)]="childVisibility">
</app-child-component>

child.component.ts

@Component({
  selector: 'app-child-component',
  templateUrl: './app-child.component.html',
  styleUrls: ['./global-search-results.component.scss']
})
export class ChildComponent {
  @Input() visible: boolean;

  constructor() {}

  public changeVisible() { 
    this.visible = false;
  }
}

child.component.html

<button (click)="changeVisible()">
  Change Visible
</button>
ame
  • 773
  • 9
  • 21
  • 1
    Possible duplicate of https://stackoverflow.com/questions/42006770/angular2-component-input-two-way-binding – Shumail Sep 25 '19 at 11:31
  • can please what you trying to do here >> trying to accept as input or emit as output – harkesh kumar Sep 25 '19 at 11:35
  • 1
    Possible duplicate of [Angular2 Component @Input two way binding](https://stackoverflow.com/questions/42006770/angular2-component-input-two-way-binding) – Igor Sep 25 '19 at 11:42

2 Answers2

1

Try like this:

child.component.ts:

@Output() visibleChange = new EventEmitter();

public makeVisible() { 
   this.visible = false;
   this.visibleChange.emit(this.visible)
}

parent.component.html

<app-child-component [(visible)]="childVisibility" >
</app-child-component>

Working Demo

Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
  • Not bad custom example but you forgot about the dependency in the naming between `visible` and `visibleChange`. I mean the next: `@Input() visible: boolean; @Output() visibleChange = new EventEmitter();` – ame Sep 25 '19 at 11:49
  • Which dependency? – Adrita Sharma Sep 25 '19 at 11:50
  • The cause is the suffix 'Change' in the event's name visibleChange. I mean this. – ame Sep 25 '19 at 12:07
1

child.component.ts

@Input()  visible: boolean;
@Output() visibleChange = new EventEmitter<boolean>();

public changeVisible() { 
   this.visible = false;
   this.visibleChange.emit(this.visible);
}

parent.component.html

<app-child-component [(visible)]="childVisibility">
</app-child-component>

The cause here is the suffix 'Change' in the event's name visibleChange. If the property binding name is 'x', the event binding name should be exactly 'xChange'. Only then angular recognizes banana-in-a-box [()] syntax.

Detailed example: http://embed.plnkr.co/Jcu0iNkaUeRF7KEF7wA4/

ame
  • 773
  • 9
  • 21