Home > Blockchain >  initializing a field in an interface
initializing a field in an interface

Time:12-04

I want to initialize a patientId in an interface with the value idfrom another component

My Interface

export class Labtest {
 
    patientId!:string   
}

PatientDetailsComponent

export class PatientDetailsComponent implements OnInit {

  ...
  ngOnInit(): void {
  const id=this._route.snapshot.paramMap.get('id');
   console.log(id);
}
}

How can i do this ?

CodePudding user response:

You can't initialize an interface. Interfaces do not have default values either. You can extend a base class that has the default values you want instead.

CodePudding user response:

You can pass the patientId value from the PatientDetailsComponent to the Labtest interface by using a property binding.

In the PatientDetailsComponent template, you can add the following code:

<app-labtest [patientId]="id"></app-labtest>

This will bind the patientId property of the Labtest interface to the id property of the PatientDetailsComponent.

In the Labtest interface, you can add an input property to receive the bound patientId value:

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

export class Labtest {
@Input() patientId: string;
}

This will allow the Labtest interface to receive the patientId value from the PatientDetailsComponent.

CodePudding user response:

You can use the setter and getter methods in your Labtest interface to set and get the patientId.

In the PatientDetailsComponent, you can use the setter method to set the patientId in the Labtest interface using the id value from the route parameter.

Here is an example:

// Labtest interface
export class Labtest {
private _patientId: string;

set patientId(patientId: string) {
this._patientId = patientId;
}

get patientId(): string {
return this._patientId;
}
}

// PatientDetailsComponent
export class PatientDetailsComponent implements OnInit {
labtest: Labtest;

constructor() {
this.labtest = new Labtest();
}

ngOnInit(): void {
const id = this._route.snapshot.paramMap.get('id');
this.labtest.patientId = id;
}
}

Now you can use the getter method in the Labtest interface to get the patientId value in other parts of your code.

Here is an example:

console.log(this.labtest.patientId); // outputs the patientId value
  • Related