13

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

1 Answer 1

20

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

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

1 Comment

Well, must be something in my code, hence getting that silly -1 from a angry someone. The emitter in your example is not doing anything, so you can just remove it. The getter/setter alone is fine. Thanks for answering.

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.