我正在尝试创建一个我创建了data-table component
,col-header directive
和col-body directive
的数据表组件。我们的想法是从col-header directive
获取列标题的标签,来自col-body directive
的值然后data-table component
呈现数据表。但问题是
@Input
传递给指令的值。col-header
data-table
组件中@ContentChildren
指令的引用
醇>
请考虑我刚开始学习角度2而且我不太擅长。 我的代码设置如下
DataTableComponent.ts
@Component({
selector: 'data-table',
template: `
<table class="table table-bordered table-striped">
<thead>
<tr *ngFor="let header of headders ">
<ng-template></ng-template>
<td>{{header.label}}</td>
</tr>
</thead>
<tbody>
<ng-template></ng-template>
</tbody>
</table>,
styleUrls: ['./data-table.component.css']
})
export class DataTableComponent implements OnInit {
@ContentChildren(Header) headers: QueryList<Header>;
}
@Input() items: User[];
ngOnInit() {
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes)
console.log(this.headers)
}
}
ColHeaderComponent.ts
@Directive({
selector: 'col-header',
})
export class Header implements OnInit {
constructor() {
}
@Input() label: string;
@Input() value: any;
ngOnInit() {
console.log(this.label)
}
ngOnChanges(changes: SimpleChanges): void {
let chng = changes['label'];
console.log(chng)
}
}
我使用它如下
<data-table [items]="users">
<col-header [label]="Name"></col-header>
<col-header [label]="Password"></col-header>
<col-body [column]="username"></col-body>
<col-body [column]="password"></col-body>
</data-table>
我还没有写过col-body
指令的任何内容,因为我还没有到达那里。请耐心检查代码,因为可能会有很多错误。
我只想简单了解如何使用@Input
获取组件的价值以及如何使用@ContentChildren
获取儿童指令的参考
由于
答案 0 :(得分:1)
试试这个
@ContentChildren(forwardRef(() => Header), {descendants: true}) headers: QueryList<Header>;