如何在javascript中的现有对象属性上定义setter

时间:2018-09-24 15:18:23

标签: javascript typescript ecmascript-6

如何在javascript ES6概念中为现有对象属性定义设置器。 目前,我已将值直接分配为true,我想通过使用setter来实现相同的目的。

HTML:

<form #Form="ngForm" novalidate (ngSubmit)="saveForm()">
<label class="radio-inline pr-3">
<input type="radio" name="isCitizen" required value="yes [(ngModel)]="formList.isCitizen" #isCitizen="ngModel"> Yes
</label>
<label class="radio-inline">
<input type="radio" name="isCitizen" required value="no"[(ngModel)]="formList.isCitizen"#isCitizen="ngModel"> No
</label>
<form>

组件:

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

 @Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ]
 })
 export class AppComponent  {
 name = 'Angular';
 formList: FormModel = new FormModel();

 saveForm(){ //how to set the value to object using setter
 if(this.formList.isCitizen === 'yes'){
 this.formList.isCitizen = true;
 }else{
 this.formList.isCitizen = false;
 }
 }
 }

 export class FormModel {
 isCitizen : boolean;
 }

Demo

1 个答案:

答案 0 :(得分:0)

在打字稿中使用

export class FormModel {
    private  _isCitizen : boolean;

    set isCitizen(isCitizen:boolean) {
        this._isCitizen = isCitizen;
    }
    get isCitizen():boolean {
       return this._isCitizen ;
    }
}