【问题标题】:Angular 5 Pass data from table in one component to anotherAngular 5将数据从一个组件中的表传递到另一个组件
【发布时间】:2018-08-02 19:58:10
【问题描述】:

我已经看到几个讨论这个问题的线程,但我仍然对什么是适合我的情况的正确方法感到困惑,所以我会尝试一下。

背景。我有一个 .net mvc 应用程序,我添加了 angular 5,现在我一点一点地用 angular 组件替换 Jquery 脚本。

所以,我有一个列出客户的列表组件,在此列表中,您有客户信息和一个复选框。如果您单击此列表中的任何复选框,菜单栏上有一个名为"move customer" 的按钮,从'disabled' 变为能够推送。

如果您按下此按钮,则会弹出一个带有 'li' 的视图,其中包含您选中其复选框的客户的姓名。客户 ID 的隐藏元素也在此 'li' 中的 'tr' 上。

我想要的是用角度重复这个。因此,监听复选框的点击,取消禁用 move-btn 并将数据发送到其他组件。并且可能有几个客户被检查,所以这必须是一个连续的事情,可能是一个列表或订阅,不断发送数据并填写接收者列表。然后它应该在另一个组件上列出名称和 ID。

** 更新 **

这是我目前拥有的:

这是我的服务,用于从列表组件发送数据以重新定位弹出框组件:

import { Injectable, EventEmitter  } from '@angular/core';
import { EmployeeDataAttributeComponent } from './components/employee/employee.data.attribute.component';

@Injectable()
export class TableRowDataService {

    employeeDataAttribute = new EventEmitter<EmployeeDataAttributeComponent>();

    send(empDataObj: EmployeeDataAttributeComponent) {
        this.employeeDataAttribute.emit(empDataObj);
    }
}

我的列表组件:

当您选中复选框时,'tr class="gridrow"' 就是类 '.selected''tr' 也有我想要的数据作为数据属性,称为 'attr.data-employment-name''attr.data-employment-personkey',我希望这两个用于每个检查或 'selected' 'tr'

<div>    
    <table class="employment-list new-style" *ngIf="filteredEmployees && filteredEmployees.length"
           attr.data-employment-organisation-nr="{{ filteredEmployees && filteredEmployees[0]?.EmploymentReference.OrganizationRegistrationNumber.FullValue }}">
        <thead>
          .....
        </thead>
        <tbody>
    <tr class="gridrow" 
        id="ngCheckRow" 
        #ngCheckRow 
        *ngFor="let employee of filteredEmployees" 
        attr.data-employment-name="{{employee.Name }}" 
        attr.data-employment-personkey="{{employee.PersonKey.CountryCode}}_{{employee.PersonKey._displayValue }}" 
        attr.data-employment-unitId="{{ unitId }}">
                <td><input type="checkbox"            
                    (change)="getdataAttributes({{employee.Name }}, {{employee.PersonKey.CountryCode}}_{{employee.PersonKey._displayValue }})"></td>
                <td id="pKey">
                    {{employee.PersonKey._displayValue}}
                </td>
                <td>AND SO  ON....</td>
            </tr>
        </tbody>
    </table>
</div>

export class EmployeeListComponent {
    .....
    empDataAttrObj: EmployeeDataAttributeComponent;
    //EmployeeDataAttributeComponent only contains two string props, name andpersonkey
    
getdataAttributes(attrName: string, attrPersonKey: string) {

    this.empDataAttrObj.name = attrName;
    this.empDataAttrObj.personKey = attrPersonKey;

    this.tableRowDataService.send(this.empDataAttrObj);
   }
}

这是我的重定位组件(将显示每个已检查客户的弹出框视图)以及我现在的想法。在'relocateForm' 中,jQuery 是用来执行此操作的。

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ButtonClickService } from '../../button.click.service';
import { TableRowDataService } from '../../table.row.data.service';
import { EmployeeDataAttributeComponent } from '../employee/employee.data.attribute.component';

@Component({
    selector: 'relocate-employment-popover',
    templateUrl: './relocate.employments.popover.html'
})
export class RelocateEmploymentsPopoverComponent {
    .....
    empDataAttrList: EmployeeDataAttributeComponent[];
    isAlreadyInList: boolean;


    constructor(private route: ActivatedRoute,
        private buttonClickService: ButtonClickService,
        private tableRowDataService: TableRowDataService) {
          ........
    }

    ngOnInit() {
        this.buttonClickService.showRelocatePopOver.subscribe((relocateCLick: boolean) => {
            this.showPopover = relocateCLick;
            if (this.showPopover) {
                this.clearSearch();
            }
        });
    }

    //Get the data
    eventEmitterSubscription = this.tableRowDataService.employeeDataAttribute.subscribe(
        (dataAttrObj: EmployeeDataAttributeComponent) => {
            this.updateList(dataAttrObj);
        });

    //Check if it already exists in list, if true remove, else add.
    updateList(dataAttrObj: EmployeeDataAttributeComponent) {
        this.isAlreadyInList = this.contains(this.empDataAttrList, dataAttrObj);

        if (this.isAlreadyInList) {
            this.empDataAttrList = this.empDataAttrList.filter(item => item !== dataAttrObj);
        } else {
            this.empDataAttrList.push(dataAttrObj);
        }
    }

    contains(arr: EmployeeDataAttributeComponent[], obj: EmployeeDataAttributeComponent) {
        const proxy = new Set(arr);
        return proxy.has(obj);
    }
    
.....

}
............
                            <div class="input-column">
                                <ul class="selected-employments" *ngFor="let employee of empDataAttrList">
                                    <li>
                                        <span>{{ employee.name }}</span>
                                        <input type="hidden" name="EmploymentPersonKeys" value="{{ employee.personKey }}">
                                    </li>
                                </ul>
                                <span class="field-validation-valid hint" attr.data-valmsg-for="EmploymentPersonKeys" attr.data-valmsg-replace="true"></span>
                            </div>
....................

【问题讨论】:

    标签: angular model-view-controller angular5


    【解决方案1】:

    看来您有一些需求,第一个是:

    监听复选框的点击

    为此,请使用标准输入元素(type="checkbox")和 Angular 的(更改)操作,例如:

    <input type="checkbox"(change)="changeAction(id, $event.target.value)">
    

    通过将被点击元素的 id 传递给组件,您可以将其添加到列表中。您还可以传递一个 $event 对象(DOM 复选框)并访问其 target.value 属性,在您的情况下,该属性将是 true(选中复选框)或 false(未选中)

    取消禁用 move-btn

    使用 Angular 的 [disabled' 指令:

    再次,当您传递行的 id 时,在您的组件中创建 isDisabled(id) 方法。在该方法中,您只需检查它之前是否被选中(见上一点)

    将数据发送到其他组件

    我不确定您需要传递哪些数据,如果它是选定元素的列表,那么使用组件上的 @Input 指令或使用服务并以这种方式共享数据很容易。

    在这种情况下,您似乎应该使用服务。因此,编写一个服务和一个包含您的数据的属性。然后,您的组件将提供两种方法(Setter 和 getter),允许您在它们之间共享数据。您还可以在服务中编写 EventEmitters 并引发事件,以便订阅者组件收到更改通知,如下所示:

    在您的服务中,声明并创建:

    public eventEmitter = new EventEmitter<YourType>();
    

    然后在你的服务的 setter/update 方法中,做:

    this.eventEmitter.emit(this.dataObjectYouWantToPass);
    

    现在,您需要做的最后一件事是在您的组件(需要修改更改的组件)中,订阅服务的 EventEmitter:

    this.eventEmitterSubscription = this.service.eventEmitter.subscribe(
                () => {
                    this.doSomethingWhenTheDataChanges();
                });
    

    【讨论】:

    • 嗨,迟到的答案很抱歉。 “通过”也许是错误的词,我的意思是分享。这是两个不同的组件,我希望包含对象和表的组件将所选 tr 的两个数据属性共享给另一个组件。
    • 我不确定更改是如何工作的,可以更具体吗?如果取消选中该复选框会怎样?
    • 另外,按钮本身就是另一个组件,必须通知复选框的选中/取消选中..
    • 根据您的第一个提示对列表组件进行了编辑。还添加了来自 listcomponent 的代码以显示功能
    • 我已经编辑了我的答案以包含更多详细信息,您可以如何将(更改)指令与复选框一起使用,以及您可能希望如何使用服务和 eventEmitter 在组件之间共享数据。
    猜你喜欢
    • 1970-01-01
    • 2017-11-29
    • 2019-12-16
    • 1970-01-01
    • 2019-09-02
    • 1970-01-01
    • 2021-07-08
    • 2018-05-02
    相关资源
    最近更新 更多