访问 ng-template 的子项

access to children of ng-template

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

有一个table创作:

<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 中获取该输入?

为了获得 input 的访问权限,请尝试将井号 test 设置为 input,而不是 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”> number is incorrect </span>