问题描述
child-component.html
<p-table
[value]="data"
[autoLayout]="true"
[loading]="loading"
[(selection)]="selectedItems" #dt
>
child-component.ts
@Component({
selector: "manager-grid",templateUrl: "./grid.component.html",styleUrls: ["./grid.component.scss"],encapsulation: ViewEncapsulation.None
})
export class GridComponent implements OnInit {
public _data: Array<any>;
public _settings: any;
public _loading: boolean;
public total = 100;
public selectedItems: any[];
public _columnFilters: any;
@ViewChild('dt') table: Table;
现在,我将该组件包括在父组件中,如下所示:
<manager-grid [data]="data" [settings]="tableSettings" [loading]="isLoading"></manager-grid>
子组件以模态添加,因此当我尝试访问selectedItems
变量时,它返回undefined
。我为此使用以下代码:
@ViewChild(GridComponent) gridComponent: GridComponent;
const items = this.gridComponent.selectedItems;
我正在使用NG Bootstrap模态,我认为问题在于,在初始化页面时,子组件不像在模态中那样是DOM的一部分。如何访问模态内部的元素?有什么解决方法吗?
解决方法
如果您有打开方式的方法,请在方式打开后访问selectedItems
。您可以尝试以下-
openModal() {
// open modal code goes here
if (this.gridComponent) {
items = this.gridComponent.selectedItems;
}
}
如果它不起作用,则可以尝试settimeout-
setTimeout(() => {
if (this.gridComponent) {
items = this.gridComponent.selectedItems;
}
},0);