M
M
Mikenzzz2017-07-27 18:54:25
JavaScript
Mikenzzz, 2017-07-27 18:54:25

How to extend a class (add a new attribute to the class object) programmatically?

The following situation:
Assume there are the following classes (TypeScript pseudocode):

class Project {
  id: number;
  name: string;
  stages: Stage[];
  constructor() {
    this.stages = []
  }
}

class Stage {
  id: number;
  name: string;
  jobs: Job[];
  constructor() {
    this.jobs= []
  }
}

class Job {
  id: number;
  name: string;
}

We have a list of projects (Project[]), to which work stages are attached (Stage[]), to which specific jobs are attached (Job[]).
There is a form with a list of projects, you can fall into a specific project. On the project change form, you can bind (add) specific stages and works to the project by marking them with checkboxes. But the Stage and Jobs classes do not have the checked attribute: boolean. How to programmatically add an attribute? How and where to store objects that have checked === true, so that later with a put request to update the project on the backend?
Here is a small example of a component in Angular:
@Component 
export class ProjectFormComponent implements OnInit {
 constructor (private projectService: ProjectService) { }
 projects: Projects[];
 
 onInit() {
   this.projectService.getPorjects()
             .subscribe(projects => this.projects = projects);
 }

 OnEditProjectButtonClick(project) {
    this.projectService.getStageByProjectID(project)
               .subscribe(stages => {
                  project.stages = stages (как то нужно добавить атрибут checked к объекту stages)
                  project.stages.filter(stage => stage.checked) (но у нас нет свойства checked)
             }
  }
}

Sample:
<ul>
    <li *ngFor="let stage of project.stages">
       <input type="checkbox" [checked] = "stage.checked" (вот здесь необходимо свойство checked, а его нет в классе)
        {{stage.name}}
    </li>
</ul>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
denismaster, 2017-07-28
@Mikenzzz

can be used. Or Finally, you can define the IChecked interface and type it:stage['checked']
stage: Stage & IChecked

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question