ngx-bootstrap学习笔记(一)-popover

前言

这月做了个ng2模块,其中有个校验功能,当校验不通过时给出提示,项目中使用jQuery实现,今天才发现ngx-bootstrap已经有现成功能了,且可封装成通用组件放入shareModule,使用方便。故记录如下。

安装

npm install ngx-bootstrap --save

引入模块

import {PopoverModule} from 'ngx-bootstrap/';

@NgModule({
  declarations: [XxxComponent...],
  imports: [
    BrowserModule,
    PopoverModule.forRoot(),
    FormsModule
  ],
  providers: [XxxService...],
  bootstrap: [XxxComponent]
})

封装组件

popover.component.ts

import {Component, ViewChild} from '@angular/core';
import {PopoverDirective} from 'ngx-bootstrap';

@Component({
  selector: 'nepsd-popover',
  templateUrl: './popover.component.html',
  styleUrls: ['./popover.component.css']
})
export class PopoverComponent {
  @ViewChild('pop') popover: PopoverDirective;
}

popover.component.html

<span popover #pop="bs-popover">
  <ng-content></ng-content>
</span>

popover.component.css

	:host > > > .popover {
	  background-color: #FCFCFC;
	}
	:host > > > .popover > .arrow:after {
	  border-top-color: #FCFCFC;
	}

其他组件引用

app.component.ts

import {Component, ViewChild} from '@angular/core';
import {PopoverComponent} from './popover/popover.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  tip: string;
  @ViewChild('pop') popoverComponent: PopoverComponent;

  validInput() {
    let valid = Math.random() > 0.5;
    if (!valid) {
      /**pop config*/
      this.popoverComponent.popover.popoverTitle = undefined;
      this.popoverComponent.popover.popover = this.tip;

      this.popHover();
    }
  }

  private popHover(timeout?: number) {
    timeout = timeout ? timeout : 1000;
    this.popoverComponent.popover.show();
    setTimeout(() => {
      this.popoverComponent.popover.hide();
    }, timeout);
  }
}

app.component.html

<div style="margin-top: 100px">
  <nepsd-popover #pop>
    <input [(ngModel)]="tip" (change)="validInput()" (blur)="popHover()">
  </nepsd-popover>
</div>

效果

参考

ngx-bootstrap

posted @ 2017-12-06 22:47  舒山  阅读(1782)  评论(1编辑  收藏  举报