I have two components (not parent-child). First component has search input field that should be populated on a button click, with a value that is available in second component. Button click also happens in second component. I tried Input Output, but it seems this is only for parent-child connection. I also tried to save the value I need in a service, and then fetch it in the first component through that service, but I get undefined. Appreciate help.
Here is my code:
FIRST COMPONENT
<mat-form-field>
<mat-label >
<span> {{ "SEARCH_DEVICES" | translate | uppercase }}</span>
</mat-label>
<input type="text" formControlName="actorDevice" matInput />
</mat-form-field>
SECOND COMPONENT
TS
passDevice(id: string) {
this.deviceService.getDeviceById(id).subscribe((res) => {
this.deviceName = res.deviceName[0].name;
});
this.deviceService.selectedDeviceName = this.deviceName;
}
HTML
<ng-container matColumnDef="selectRow">
<mat-header-cell *matHeaderCellDef>
{{ "SELECT" | translate }}
</mat-header-cell>
<mat-cell *matCellDef="let row">
<button mat-button type="button" (click)="passDevice(row.id)">
Select
</button>
</mat-cell>
</ng-container>
CodePudding user response:
You are setting selectedDeviceName in service before data is returned from API. Thats why it is undefined. You need to set it inside subscription
passDevice(id: string) {
this.deviceService.getDeviceById(id).subscribe((res) => {
this.deviceName = res.deviceName[0].name;
this.deviceService.selectedDeviceName = this.deviceName;
});
CodePudding user response:
As soon as I posted the question, I found the solution. I have used a service in which I have defined a variable of type Subject (rxjs), and used it in first component to fill the variable with the value I need, and then in the second component I have fetched this value and passed it in the html input field.
SERVICE
export class SearchAppointmentService {
addName: Subject<string>;
constructor() {
this.addName = new Subject<string>();
}
}
FIRST COMPONENT
this.deviceService.getDeviceById(id).subscribe((res) => {
this.deviceName = res.deviceName[0].name;
this.searchAppointmentService.addName.next(this.deviceName);
});
SECOND COMPONENT
addNameSubscription: Subscription;
this.addNameSubscription = this.searchAppointmentService.addName.subscribe(
(res) => {
this.inputDeviceName = res;
}
);
HTML
<input
type="text"
formControlName="actorDevice"
matInput
[value]="inputDeviceName | uppercase"
/>