微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Angular中使用ViewChild访问模态内部的子组件

如何解决在Angular中使用ViewChild访问模态内部的子组件

我有一个PrimeNG表作为子组件,它具有以下代码

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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。