Angular 2, @ Incoming Receiver / Setter

I work in an angular project, we also use angularjs components.

Instead of using the @input variable, I wanted to use getter and seters, but came across the following below. I'm curious how, but it's hard for me to find information about this.

it 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;
    }

is not

<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 explain to me why?

thank

+4
source share
1 answer

Perhaps in the second version you are missing Event Emitter for two-way binding.

You need to add abcChange

Please see this demo here - it works great:

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

+6
source

Source: https://habr.com/ru/post/1676470/


All Articles