Bootstrap popover内部失败*ngIf处于角度



我试图在容器内显示popover,但它不起作用,

如果我删除*ng如果它工作

如果*ng如果它不呈现

<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
})
}
}```

这不起作用,因为当ngOnInit((由angular调用时,div.container未由angular渲染。相反,您可以使用AfterViewInit生命周期挂钩,如下所示。

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

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

component.html

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

组件.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)

最新更新