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>
3

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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<boolean>();
Which dependency?
The cause is the suffix 'Change' in the event's name visibleChange. I mean this.
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.