单击按钮时有角度填充禁用的输入字段
我有两个组件(不是父子组件)。第一个组件具有搜索输入字段,应在单击按钮时填充该字段,并使用第二个组件中可用的值。按钮单击也发生在第二个组件中。我尝试了输入输出,但似乎这仅适用于父子连接。我还尝试将我需要的值保存在服务中,然后通过该服务在第一个组件中获取它,但我没有定义。感谢帮助。
这是我的代码:
第一组件
<mat-form-field>
<mat-label class="mat-uppercase has-events">
<span> {{ "SEARCH_DEVICES" | translate | uppercase }}</span>
</mat-label>
<input type="text" formControlName="actorDevice" matInput />
</mat-form-field>
第二组件
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>
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 class="mat-uppercase has-events">
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在从 API 返回数据之前,您正在服务中设置 selectedDeviceName。这就是为什么它是未定义的。您需要在订阅内设置它
You are setting selectedDeviceName in service before data is returned from API. Thats why it is undefined. You need to set it inside subscription
我一发布问题,就找到了解决方案。我使用了一项服务,其中定义了一个主题类型(rxjs)的变量,并在第一个组件中使用它来用我需要的值填充该变量,然后在第二个组件中我获取了该值并将其传递给html 输入字段。
服务
第一组件
第二组件
HTML
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
FIRST COMPONENT
SECOND COMPONENT
HTML