【问题标题】:Bootstrap popover fails inside *ngIf in angularBootstrap popover 在 *ngIf 内以角度失败
【发布时间】:2020-11-01 01:49:49
【问题描述】:

我正在尝试在容器内显示弹出框,但它不起作用,

如果我删除 *ngIf 它可以工作

如果 *ngIf 不渲染,会出现在哪里

<div class="container" *ngIf="data" >
  <button 
    class="popover" 
    data-trigger="hover" 
    data-toggle="tooltip" 
    data-content="hello" 
    data-container="body">
  <mat-icon>
   info
  </mat-icon>
 </button>
</div>

//ts 文件

export class SomeComponent implements OnInit {
//... variables 
//... constructor

  ngOnInit() {
      $('.popover').popover({
        boundary: 'viewport',
        placement: 'top',
        container:'body',
        sanitize: true,
        appendToBody: true
      })

  }
}```

【问题讨论】:

  • 这里的数据是什么,是在调用popover之前设置的吗?
  • data 是从 API 获取的数组,是的,它是在它之前设置的

标签: javascript html angular twitter-bootstrap angular-material


【解决方案1】:

这不起作用,因为在 Angular 调用 ngOnInit() 时,div.container 不是由 Angular 渲染的。相反,您可以使用 AfterViewInit Lifecycle 挂钩,如下所示。

注意,带有ngIf的段落不能在ngOnInit中加载,但可以在ngAfterViewInit中加载。

Stackblitz 代码:https://stackblitz.com/edit/angular-ngif-lifecycle-hook

component.html

<p id="p1">
  Without ngIf
</p>

<p id="p2" *ngIf="data">
  With ngIf
</p>

component.ts

import { Component, VERSION, OnInit, AfterViewInit } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit, AfterViewInit{
    data = {random: 'text'};

    ngOnInit() {
        const withoutNgIf = document.getElementById('p1');
        const withNgIf = document.getElementById('p2');

        console.log('OnInit without ngIf: ', withoutNgIf);
        # Output: HTMLParagraphElement
        console.log('OnInit with ngIf: ', withNgIf);
        # Output: null
    }

    ngAfterViewInit() {
        const withNgIf = document.getElementById('p2');  
        console.log('AfterViewInit with ngIf: ', withNgIf);
        # Output: HTMLParagraphElement
    }
}

希望能帮助你理解问题。

提示:如果您使用 angular,我建议使用 ViewChild 装饰器来访问 DOM 而不是 jquery。 (例如:https://dev.to/danielpdev/how-to-use-viewchild-decorator-in-angular-9-i0

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    相关资源
    最近更新 更多