You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 4:如何使两个HTML组件绑定同一值?

解决Angular组件间共享item.md_id的问题

嘿,作为Angular新手碰到组件间数据传递的问题太正常了,我来帮你一步步搞定~

首先先修正你现有表格代码里的小问题:<td>标签不需要用[(ngModel)]哦,这个指令是给表单输入控件(比如input、select)用的,td是纯展示元素,咱们把这块代码优化下:

<tr *ngFor="let item of driverData">
  <td class="align-right" (click)="runPromo(item)">
    {{item.driver_name}}
  </td>
</tr>

接下来分两种情况解决你“在另一个组件里使用item.md_id”的需求:

情况1:两个组件是父子关系

如果你的表格组件是父组件,目标按钮组件是它的子组件(比如按钮组件是通过<app-button-component>这类标签嵌入在表格组件页面里的),可以用@Input()来传递数据:

  1. 在父组件(表格所在组件)的TS文件里:
    定义一个变量存储选中的md_id,然后在runPromo方法里赋值:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-driver-table',
      templateUrl: './driver-table.component.html'
    })
    export class DriverTableComponent {
      driverData: any[] = []; // 你的数据数组
      selectedMdId: number | undefined;
    
      runPromo(item: any) {
        this.selectedMdId = item.md_id;
        // 原来的其他逻辑也可以保留在这里
      }
    }
    
  2. 在父组件的HTML里:
    把选中的selectedMdId传递给子组件:

    <!-- 表格代码 -->
    <tr *ngFor="let item of driverData">
      <td class="align-right" (click)="runPromo(item)">
        {{item.driver_name}}
      </td>
    </tr>
    
    <!-- 目标按钮组件 -->
    <app-target-button [selectedMdId]="selectedMdId"></app-target-button>
    
  3. 在子组件(按钮所在组件)的TS文件里:
    用@Input()接收父组件传递过来的值:

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'app-target-button',
      templateUrl: './target-button.component.html'
    })
    export class TargetButtonComponent {
      @Input() selectedMdId: number | undefined;
    
      runPromo(id: number | undefined) {
        if (id) {
          // 这里处理你的按钮点击逻辑,使用id
          console.log('选中的md_id:', id);
        }
      }
    }
    
  4. 子组件的HTML里:
    直接使用接收过来的值:

    <div>
      <button class="active" [value]="selectedMdId" (click)="runPromo(selectedMdId)">
        First...
      </button>
    </div>
    

情况2:两个组件是同级/无直接关系

如果两个组件没有父子关系(比如都是路由导航出来的,或者嵌入在同一个父组件但互相独立),那用Angular服务来共享数据是最靠谱的方式:

  1. 创建一个共享数据服务:

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs';
    
    @Injectable({
      providedIn: 'root' // 全局提供这个服务
    })
    export class DataShareService {
      // BehaviorSubject会保存最新的值,新订阅的组件能拿到当前最新值
      private selectedMdIdSubject = new BehaviorSubject<number | undefined>(undefined);
      selectedMdId$ = this.selectedMdIdSubject.asObservable();
    
      setSelectedMdId(id: number) {
        this.selectedMdIdSubject.next(id);
      }
    }
    
  2. 在表格组件的TS文件里:
    注入服务,在runPromo方法里设置选中的id:

    import { Component } from '@angular/core';
    import { DataShareService } from './data-share.service';
    
    @Component({
      selector: 'app-driver-table',
      templateUrl: './driver-table.component.html'
    })
    export class DriverTableComponent {
      driverData: any[] = [];
    
      constructor(private dataShareService: DataShareService) {}
    
      runPromo(item: any) {
        this.dataShareService.setSelectedMdId(item.md_id);
        // 原来的其他逻辑
      }
    }
    
  3. 在目标按钮组件的TS文件里:
    注入服务,订阅选中的id:

    import { Component, OnInit } from '@angular/core';
    import { DataShareService } from './data-share.service';
    
    @Component({
      selector: 'app-target-button',
      templateUrl: './target-button.component.html'
    })
    export class TargetButtonComponent implements OnInit {
      selectedMdId: number | undefined;
    
      constructor(private dataShareService: DataShareService) {}
    
      ngOnInit() {
        // 订阅选中的id,一旦有变化就更新本地变量
        this.dataShareService.selectedMdId$.subscribe(id => {
          this.selectedMdId = id;
        });
      }
    
      runPromo(id: number | undefined) {
        if (id) {
          console.log('选中的md_id:', id);
          // 按钮点击逻辑
        }
      }
    }
    
  4. 目标按钮组件的HTML不变:

    <div>
      <button class="active" [value]="selectedMdId" (click)="runPromo(selectedMdId)">
        First...
      </button>
    </div>
    

这样不管是哪种情况,你都能在目标组件里拿到选中的item.md_id啦~

内容的提问来源于stack exchange,提问作者Neha Uniyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:05:20