假设我有两个组件--父组件和子组件,并且我试图从父组件访问子组件的DOM元素。但我面临的问题是未定义的原生元素。
export class ChildComponent implements OnInit,AfterViewInit{
@ViewChild('pdfData', { read: ElementRef }) domData: ElementRef;
constructor()
ngOnInit(): void {
some code..
}
ngAfterViewInit(): void {
this.domData.nativeElement;
}
}
子组件DOM元素
<div #pdfData class="pdfData">
<table *ngFor="let hubxReport of hubxReportList; let i=index">
<tr>
<th>{{hubxReport.categoryName}} + "Test"</th>
</tr>
<tr>
<th>{{column}}</th>
</tr>
<tr *ngFor="let item of hubxReport.hubxDataItems">
<td></td>
<td>{{item.itemTitle}}</td>
<td>{{item.itemValue}}</td>
<td>{{item.itemUnit}}</td>
<td>{{item.normalRange}}</td>
</tr>
</table>
</div>
下面的代码是父组件,我正在尝试访问子组件DOM元素,问题就在这里。
export class ParentComponent implements OnInit,AfterViewInit{
@ViewChild('pdfData',{ read: ElementRef }) pdf: ChildComponent ;
constructor()
ngOnit(): void{
some code...
}
ngAfterViewInit() {
this.pdf.domData.nativeElement;
console.log(this.pdf.domData.nativeElement) //undefine here
}
downloadPDF(isSubmit:any) {
debugger
let doc = new jsPDF();
let rows: Array<any> = [];
let header: Array<any> = [];
let medicineInfo: any;
let physicianInfo: any;
//this.isShow = true;
//this.changeRef.detectChanges();
let content= this.pdf.domData.nativeElement; //undefine here
let _elementHandlers =
{
'#editor':function(element,renderer){
return true;
}
};
doc.html(content.innerHTML,{
callback: function (doc) {
doc.save();
},
x: 10,
y: 80,
// 'x': 15,
// 'y': 15,
width:190,
'elementHandlers':_elementHandlers
});
}
这是我的Stackblitz 链接
发布于 2022-10-18 23:44:47
您的"pdfData“模板引用变量属于”子“,因此不能从”父“访问使用viewChild。
你可以做父母
<div class="col-sm-6">
<!--in click button you pass a template reference variable of the child-->
<button ... (click)="downloadPDF(child,false)" >
Print
</button>
<!--see that you use a template reference variable in child-->
<my-child #child></my-child>
</div>
您的函数downloadPDF
downloadPDF(child:any,isSubmit: any) {
....
let content = child.domData.nativeElement; //see how access to the property
//domData of the "child"
//yes, by defect all the variables in Angular are public
//include the variables that makes reference
//to viewChild
...
}
见您的叉式堆栈闪电战
注意:在声明没有变化的变量时,应该使用"const“(而不是let),例如,const content=..
比let content=...
好
发布于 2022-10-19 00:27:56
在stackblitz中,您根本没有使用my-child
元素。
您可以尝试访问子变量中的pdfData
,然后在父变量中访问该变量。
因此,domData
是一个在子变量中声明的变量,它从pdfData
读取,因此它只存在,并且可以从子对象访问。因为您的父服务器上不存在pdfData
,所以从这里用ViewChild
读取它将返回undefined
,因此您必须在子节点中声明domData
。
但是,您可以使用ViewChild
访问子变量中的html变量,并将其放入组件变量(就像您试图对父变量所做的那样)。
然后,在父母身上你可以<my-child #myChild></my-child>
和
ViewChild('myChild', read: ChildComponent) myChildComponent
。
这将使您能够访问所有的子属性,包括来自子属性中的子pdfData
的ViewChild
(单词是令人困惑的)
myChildComponent.pdfData.nativeElement
on AfterViewInit
https://stackoverflow.com/questions/74121154
复制相似问题