简体   繁体   中英

how to define a setter on existing object property in javascript

How to define a setter for existing object property in javascript ES6 concept. Currently, I've directly assigned the value to true, I would like to achieve the same by using 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>

Component:

 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

In typescript use

export class FormModel {
    private  _isCitizen : boolean;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM