angular - 访问 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 中获取该输入?
解决方案
为了访问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>
推荐阅读
- vue.js - 将数组作为未在其他组件上收到的道具传递
- scala - 我们可以通过保存 parquet 文件来复制 Spark 的 .cache() 行为吗?
- javascript - Javascript 计数器在滚动时开始
- python - NLTK:如何使用 python 在循环中获取数组的特定内容?
- node.js - Node.js 模块:导出异步函数
- javascript - 一起使用 onclick 函数和 href
- spring-boot - 时区 Springboot Tomcat 8 AS
- java - 你如何证明或说明快速归并排序是一种不稳定的算法?
- html - 我想将导航栏的 UL 元素向右对齐
- python - 多个字典的单个 for 循环