typescript Angular 2,@Input getter/setter

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43804416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:30:54  来源:igfitidea点击:

Angular 2, @Input getter/setter

angulartypescript

提问by Edgar

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

我在一个 angular 项目中工作,我们也使用 angularjs 组件。

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.

我想使用 getter 和 setter,而不是使用 @input 变量,但遇到了以下问题。我很好奇如何,但我发现很难找到这方面的信息。

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

谢谢

回答by Tiep Phan

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

也许在第二个版本中,您缺少双向绑定工作的事件发射器。

You need add abcChange

你需要添加 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

在线演示:http: //plnkr.co/edit/y9GVu7?p=preview