0

Angular Two way binding

is in any case we can have

[(ngModel)] --> [(propertyName)] is this possible this has been asked to me in interview???

1
  • Yes it does work in a way, you would have to use @Input and @Output Commented May 25, 2020 at 20:27

1 Answer 1

1

Yes, you can use two-way binding in many cases. There are a lot of examples in the official docs.

In cases where you have a component with an @Input and an @Output you can use it.

If this is your component:

src/app/sizer.component.ts

import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-sizer',
  templateUrl: './sizer.component.html',
  styleUrls: ['./sizer.component.css']
})
export class SizerComponent {


  @Input()  size: number | string;
  @Output() sizeChange = new EventEmitter<number>();

  dec() { this.resize(-1); }
  inc() { this.resize(+1); }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }

}

src/app/sizer.component.html

<div>
  <button (click)="dec()" title="smaller">-</button>
  <button (click)="inc()" title="bigger">+</button>
  <label [style.font-size.px]="size">FontSize: {{size}}px</label>
</div>

You can use it as follows:

<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>

The secret here lies between suppose you wanted to have two way binding on size. So there should be one input with name size and one output with name sizeChange. This naming convention ensures to automatically bind it.

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

2 Comments

Output property name should be @Output() sizeChange = new EventEmitter<number>(); size right???
if input name is size. Yes its mandatory to have name sizeChange for two way binding.

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.