如何在输入字段模型属性的角度中制作getter和setter?

时间:2018-05-05 13:47:43

标签: javascript angular

你能告诉我如何制作输入字段属性的getter和setter。 我试过这个

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
      private _keyValue: string;
      get KeyValue(): string{
        return this._keyValue;
    }

    set KeyValue(value: string){
      console.log('====')
        this._keyValue = value;
    }

  name = 'Angular 6';
}

当我输入输入字段时,我的console不打印为什么? 这是我的代码 https://stackblitz.com/edit/angular-vnvv6b?file=src%2Fapp%2Fapp.component.ts

1 个答案:

答案 0 :(得分:1)

您未使用自己创建的setter,而是直接绑定到_keyValue

要绑定到您的setter,您必须使用

<input [(ngModel)]="KeyValue"/>

由于KeyValue是您的二传手的名称

相关问题