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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With