假設我有兩個組件父組件和子組件,我正在嘗試從父組件訪問子組件的 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鏈接
uj5u.com熱心網友回復:
您的“pdfData”模板參考變數屬于“child”,因此您無法使用“parent”中的 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>
您的功能下載PDF
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”(不讓),例如,const content=..優于let content=...
uj5u.com熱心網友回復:
在您的 stackblitz 中,您根本沒有使用my-child元素。
您可以嘗試pdfData在子項中訪問,然后在父項中訪問該變數。
因此,domData是一個在子級中宣告的變數,它從子級中讀取,pdfData因此它只存在并且可以從子級訪問。由于pdfData您的父母不存在,ViewChild從這里閱讀它會回傳undefined,所以您必須domData在孩子中宣告。
但是,您可以訪問子級中的 html 變數ViewChild并將其分配給組件變數(就像您嘗試在父級上執行的操作一樣)。
然后,在父母身上,你<my-child #myChild></my-child>可以
ViewChild('myChild', read: ChildComponent) myChildComponent.
這應該使您可以訪問所有子屬性,包括pdfData來自子屬性的子屬性ViewChild(單詞令人困惑)
myChildComponent.pdfData.nativeElement上AfterViewInit
分叉的堆疊閃電戰
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/518186.html
標籤:有角度的
