前言
父向子传值(父组件通过属性传值给子组件,子组件通过@input方式来接受)\
父组件
<app-parent [data]="data"></app-parent>
子组件
<app-child></app-child>
@Input('data')
子向父传值(子组件通过@Output方式发出,父组件通过属性方式接受)
子组件
<app-child></app-child>
//创建一个事件发射器
@Output() add = new EventEmitter();
父组件(属性接受)
<app-parent [add]="getData($event)"></app-parent>
一、创建table组件(子组件)
ng g c custom-table
custom-table.component.html
<nz-table #basicTable [nzData]="listOfData">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let data of basicTable.data">
<td>{{ data.name }}</td>
<td>{{ data.age }}</td>
<td>{{ data.address }}</td>
<td nzAlign="center">
<a (click)="editalertrule(data)">编辑</a>
<nz-divider nzType="vertical"></nz-divider>
<a (click)="delalertrule(data.id)">删除</a>
</td>
</tr>
</tbody>
</nz-table>
custom-table.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-custom-table',
templateUrl: './custom-table.component.html',
styles: []
})
export class CustomTableComponent implements OnInit {
@Input() listOfData;
@Output() editRow = new EventEmitter()
constructor() { }
ngOnInit() {
}
editalertrule(data) {
this.editRow.emit(data)
}
}
二、父组件中调用table子组件
<app-custom-table [listOfData]="tableData" (editRow)="edit($event)"></app-custom-table>
import { Component, OnInit } from '@angular/core';
interface Person {
key: string,
name: string,
age: number,
address: string
}
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styles: []
})
export class TestComponent implements OnInit {
tableData: Person[] = [
{
key: '1',
name: 'John Brown',
age: 32,
address: 'New York No. 1 Lake Park'
},
{
key: '2',
name: 'Jim Green',
age: 42,
address: 'London No. 1 Lake Park'
},
{
key: '3',
name: 'Joe Black',
age: 32,
address: 'Sidney No. 1 Lake Park'
}
];
constructor() { }
edit(e) {
console.log('e', e);
}
}