【发布时间】:2018-07-09 17:00:17
【问题描述】:
您好,我尝试了一个示例,例如通过自定义组件将数据从父级传递给子级,从子级传递给父级。
以下是我使用的文件。 我附上了父子组件的html和ts文件。
每个员工都有一个名为选择记录的按钮。单击按钮时,应突出显示整行。
Parent component (app.component.ts)
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
public employeeRecord: any = [
{eId: 1, eName: "sachin", eCity: "Mumbai", eSalary: 8000},
{eId: 2, eName: "Yuvi", eCity: "Panjab", eSalary: 9000},
{eId: 3, eName: "Dhoni", eCity: "Ranchi", eSalary: 800},
{eId: 4, eName: "Dravid", eCity: "Bangalore", eSalary: 8000},
{eId: 5, eName: "Anil", eCity: "Delhi", eSalary: 2000}
];
selectedRecordData: any = {
selectedEmplyoeeName: "",
selectedEmplyoeeCity: "",
selectedEmplyoeeSalary: ""
};
getSelectedRecord(data) {
this.selectedRecordData = data;
}
}
Parent Component html (app.component.html)
<h1>Employee Record List</h1>
<h1>Selected Employee</h1>
<h3>Id : {{selectedRecordData.selectedEmplyoeeId}}</h3>
<h3>Name : {{selectedRecordData.selectedEmplyoeeName}}</h3>
<h3>City : {{selectedRecordData.selectedEmplyoeeCity}}</h3>
<h3>Salary : {{selectedRecordData.selectedEmplyoeeSalary}}</h3>
<app-custom-component
[id] = "employee.eId"
[name] = "employee.eName"
[city] = "employee.eCity"
[salary] = "employee.eSalary"
(sendRecord) = "getSelectedRecord($event)"
*ngFor="let employee of employeeRecord;">
</app-custom-component>
custom-component (Custom-component.ts).
import { Component, OnInit, Input, Output, EventEmitter } from
'@angular/core';
@Component({
selector: 'app-custom-component',
templateUrl: './custom-component.component.html',
styleUrls: ['./custom-component.component.css']
})
export class CustomComponentComponent implements OnInit {
constructor() { }
ngOnInit() {
}
isSelect: false;
@Input('id') employeeId: number;
@Input('name') employeeName: string;
@Input('city') employeeCity: string;
@Input('salary') employeeSalary: number;
@Output() sendRecord: EventEmitter<any> = new EventEmitter();
public selectedRecord(event) {
let selectedEmplyoeeRecordDetails: any = {
selectedEmplyoeeId: this.employeeId,
selectedEmplyoeeName: this.employeeName,
selectedEmplyoeeCity: this.employeeCity,
selectedEmplyoeeSalary: this.employeeSalary,
};
this.sendRecord.emit(selectedEmplyoeeRecordDetails);
isSelect = true;
}
}
**Custom component (custom.component.html)**
<div [ngClass]="{'highlight': isSelect}">
<h3>Id : {{employeeId}}</h3>
<h3>Name : {{employeeName}}</h3>
<h3>City : {{employeeCity}}</h3>
<h3>Salary : {{employeeSalary}}</h3>
<button (click)= "selectedRecord(event)">SelectRecord</button>
【问题讨论】:
标签: javascript angular angular-components