Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, @Input getter/setter

I'm working in an angular project, we also use angularjs components.

Instead of using a @input variable, I wanted to use getter and setters, but came across the following bellow. I am curious to how, but am find it hard to find info on this.

this works

<foobar [(model)]="model"></foobar>

TS CODE:
    @Input() set model(value: any) {
        this._model= value;
        console.log('I am here:', value);
    }
    get model() {
        return this._model;
    }

this doesn't

<foobar [(abc)]="model"></foobar>

TS CODE:
    @Input('abc') set model(value: any) {
        this._model= value;
        console.log('I am here:', value);
    }
    get model() {
        return this._model;
    }

Could you please explain to me why?

Thanks

like image 562
Edgar Avatar asked May 05 '17 12:05

Edgar


1 Answers

Maybe in 2nd version you're missing Event Emitter for two-way binding work.

You need add abcChange

Please take a look this demo here - it's work fine:

import {Component, NgModule, VERSION, Input, Output, EventEmitter} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';


@Component({
  selector: 'tpc-ts',
  template: `
    <input [(ngModel)]="model">
    <div>{{model}}</div>
  `
})
export class TsComponent {
  _model: string;

  @Output()
  valueChange: EventEmitter<string> = new EventEmitter<string>();

  @Input('value')
  set model(value: string) {
    this._model = value;
    this.valueChange.emit(this._model);
  }

  get model() {
    return this._model;
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <tpc-ts [(value)]="name"></tpc-ts>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App, TsComponent ],
  bootstrap: [ App ]
})
export class AppModule {}

Online demo: http://plnkr.co/edit/y9GVu7?p=preview

like image 159
Tiep Phan Avatar answered Oct 13 '22 20:10

Tiep Phan