在使用Angular和Bootstrap 4开发时,我们可能会遇到Tab切换事件不会触发OnChange事件的问题。这是因为Tab的切换是由Bootstrap的JavaScript代码实现的,而不是Angular的变化检测机制。为了解决这个问题,我们可以使用Angular的@ViewChild装饰器来获取Tab组件,并监听其激活事件。以下是解决方法的示例代码:
HTML模板:
组件类代码:
import { Component, ViewChild } from '@angular/core'; import { NgbTabset } from '@ng-bootstrap/ng-bootstrap';
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent { @ViewChild('myTabSet') myTabSet: NgbTabset;
ngAfterViewInit() { this.myTabSet.tabChange.subscribe(() => { // 在这里写OnChange事件的处理逻辑 }); } }
在上面的代码中,我们使用@ViewChild装饰器来获取Tab组件的实例,并在ngAfterViewInit生命周期钩子函数中监听其tabChange事件。当Tab切换时,该事件将被触发,并可以在其中编写OnChange事件的处理逻辑。这样就可以解决Tab切换不触发OnChange事件的问题了。
上一篇:Angular,addapostajaxcalldirectlyintoanangularservice
下一篇:Angular,ngrx-store-localstorage:无法将存储在localstorage中的地图重新填充