简体   繁体   中英

Angular two way binding [(ngModel)]

Angular Two way binding

is in any case we can have

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM