如何获得角度为2的父组件中ng-content内使用的指令列表的引用

时间:2017-06-23 14:18:25

标签: angular

我正在尝试创建一个我创建了data-table componentcol-header directivecol-body directive的数据表组件。我们的想法是从col-header directive获取列标题的标签,来自col-body directive的值然后data-table component呈现数据表。但问题是

  1. 我无法将@Input传递给指令的值。
  2. 我无法使用col-header
  3. 获取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获取儿童指令的参考

    由于

1 个答案:

答案 0 :(得分:1)

试试这个

 @ContentChildren(forwardRef(() => Header), {descendants: true}) headers: QueryList<Header>;