Bootstrap сбой всплывающего окна внутри * ngIf в angular - PullRequest
0 голосов
/ 11 июля 2020
• 1000 *
<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
      })

  }
}```

1 Ответ

0 голосов
/ 11 июля 2020

Это не работает, потому что div.container не отображается angular к моменту, когда ngOnInit () вызывается angular. Вместо этого вы можете использовать ловушку AfterViewInit Lifecycle, как показано ниже.

Обратите внимание, что абзац с ngIf не может быть загружен в ngOnInit, но его можно загрузить в ngAfterViewInit.

Stackblitz код: https://stackblitz.com/edit/angular-ngif-lifecycle-hook

компонент. 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
    }
}

Надеюсь, это поможет вам понять проблема.

Совет: я бы предложил использовать декоратор ViewChild для доступа к DOM вместо jquery, если вы используете angular. (Пример: https://dev.to/danielpdev/how-to-use-viewchild-decorator-in-angular-9-i0)

...