简体   繁体   中英

Check if a value is private or readonly

Say i have a class :

export class ItemType{

  readonly itemtype_id: number;
  public name :string;

  constructor(itemtype_id: number, name: string) {
    this.itemtype_id = itemtype_id;
    this.name = name;
  }
}

Now i have made a seperate component that is an editable label.

<div class="row">
  <div class="col-xs-4">
    <h4><span class="xvrfont padding">{{label}}</span></h4>
  </div>
  <div class="col-xs-2"></div>
  <div class="col-xs-5">

    <div *ngIf="editing">
      <input #editableField
             [required]="required"
             (blur)="onBlur($event)"
             [name]="value"
             [(ngModel)]="value"
             [type]="type"
             [placeholder]="label"
             (keyup.enter)="onEnter()"
             (mouseover)="$event.target.select()"
             />
    </div>
    <div *ngIf="!editing">
      <h4 title="Click to edit" (click)="edit(value);" (focus)="edit(value);" tabindex="0" class="inline-edit">{{value}}&nbsp;</h4>
    </div>


  </div>
</div>

when i call this component, i want the field to be editable based on if the property is readonly. if the property is readonly the field should not be editable. if it isn't, it should.

<app-editable-field [isEditable]={{**check if the property is readonly**}} label='Label" [required]="true" type="text"></app-editable-field>

is there an easy way to check if a property in a class is readOnly / private?

The thing is that your Typescript gets compiled to Javascript, always keep that in mind.

So all the type and public/private checks (and all the other stuff that makes Typescript awesome) can only be performed at compilation time. All that information is lost as soon as you compiled it to Javascript. That means that there isn't really a way of checking if a member is private or readonly during runtime, since your browser is executing plain Javascript.

To illustrate this, check this link to see what your Typescript class gets compiled to: TypeScript Playground

As dsfq pointed out in the comment, use a boolean member to indicate if the field is editable or not.

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