首页 > 解决方案 > 访问 ng-template 的子节点

问题描述

我正在使用直接编辑的primeng数据表,我需要访问ng-templateng的孩子

有一个表创建:

<p-treeTable [value]="files" [columns]="cols">
    <ng-template pTemplate="header" let-columns>
        <tr>
            <th *ngFor="let col of columns">
                {{col.header}}
            </th>
        </tr>
    </ng-template>
    <ng-template pTemplate="body" let-rowNode let-rowData="rowData" let-columns="columns">
        <tr>
            <td *ngFor="let col of columns; let i = index" ttEditableColumn [ngClass]="{'ui-toggler-column': i === 0}">
                <p-treeTableToggler [rowNode]="rowNode" *ngIf="i === 0"></p-treeTableToggler>
                <p-treeTableCellEditor>
                    <ng-template #test pTemplate="input">
                        <!-- GET THIS TAG -->
                        <input pInputText type="text" [(ngModel)]="rowData[col.field]" [ngStyle]="{'width': i == 0 ? '90%': '100%'}">
                    </ng-template>
                    <ng-template pTemplate="output">{{rowData[col.field]}}</ng-template>
                </p-treeTableCellEditor>
            </td>
        </tr>            
    </ng-template>
</p-treeTable>

在我的组件中,我使用 @ViewChildren 装饰器从主机视图中获取元素:

 @ViewChildren('test') test: QueryList<TemplateRef<any>>;

 ngAfterViewInit() {
    // console.log(this.test);
    this.test.changes.subscribe(() => {
      this.test.toArray().forEach(el => {

          console.log( el);
      });
    });
  }

控制台输出:

ElementRef {nativeElement: comment}
    nativeElement: comment
    baseURI: "http://localhost:4200/"
    childNodes: NodeList(0)
    length: 0
    __proto__: NodeList
    data: "bindings={↵  "ng-reflect-name": "input"↵}"
    firstChild: null
    isConnected: false
    lastChild: null
    length: 41
    nextElementSibling: null
    nextSibling: null
    nodeName: "#comment"
    nodeType: 8
    nodeValue: "bindings={↵  "ng-reflect-name": "input"↵}"
    ownerDocument: document
    parentElement: null
    parentNode: null
    previousElementSibling: null
    previousSibling: null
    textContent: "bindings={↵  "ng-reflect-name": "input"↵}"
    __proto__: Comment
    __proto__: Object

我做错了什么?如何在 ng-template 中获取该输入?

标签: angularprimeng

解决方案


为了访问input,请尝试将井号设置testinput,而不是ng-template

<ng-template  pTemplate="input">         
     <input 
       #test 
       pInputText type="text" 
       [(ngModel)]="rowData[col.field]" [ngStyle]="{'width': i == 0 ? '90%': '100%'}">
     </ng-template>
</ng-template>

打字稿:

@ViewChildren('test') test: any;

更新:

你可以这样验证:

   <input 
       #test 
       pInputText type="text" 
       [(ngModel)]="rowData[col.field]" [ngStyle]="{'width': i == 0 ? '90%': '100%'}">
   <span *ngIf=“rowData[col.field] == 1”&gt; number is incorrect </span>

推荐阅读