使用Angular写好一个单例的Toast组件
发布时间:2020-12-17 08:59:29 所属栏目:安全 来源:网络整理
导读:新建项目 ng new mobile --style scss -sinpm i --registry=https://registry.npm.taobao.org #if error continuenpm ing serve # start a server 创建Toast组件 cd /path/mobile/src/appng -g component ToastComponent toast.component.ts //toast.compone
新建项目ng new mobile --style scss -si npm i --registry=https://registry.npm.taobao.org #if error continue npm i ng serve # start a server 创建Toast组件cd /path/mobile/src/app ng -g component ToastComponent toast.component.ts//toast.component.ts import { import { Component,OnInit,Input } from '@angular/core'; import { UtilsService } from './utils.service'; @Component({ selector: 'app-toast',templateUrl: './toast.component.html',styleUrls: ['./toast.component.scss'] }) export class ToastComponent implements OnInit { public show; public content; public duration; public type; timer:any = null; constructor(private utilsService: UtilsService) { this.show = false; this.content = ''; this.duration = 3000; this.type = 'info'; } ngOnInit() { this.utilsService.toastChange.subscribe(d => { this.showToast(d); }); } showToast(d) { clearTimeout(this.timer); this.content = d.content || ''; this.duration = d.duration || this.duration; this.type = d.type || 'info'; this.show = true; this.timer = setTimeout(() => { this.show = false; },this.duration); } } } toast.component.html//toast.component.html <div class="toast weui-toast" [hidden]="!show"> <p class="weui-toast__content"> <span *ngIf="type === 'warn'" class="warn">{{content}}</span> <span *ngIf="type === 'info'" class="info">{{content}}</span> </p> </div> toast.component.scss//toast.component.scss .weui-toast { width: initial; max-width: 300px; min-height: auto; top: auto; bottom: 60px; left: 50%; padding: 15px 15px 15px 10px; transform: translateX(-25%); } .weui-toast__content { margin: 0; color: #fff; line-height: 1.5;; text-align: left; span { position: relative; display: block; padding-left: 30px; } span:before { content: ' '; position: absolute; left: 3px; top: 1px; width: 20px; height: 20px; background: url(/assets/images/icon/toast-success.png) left center no-repeat; background-size: 100%; } span.warn:before { background: url(/assets/images/icon/login-icon-04.png) left center no-repeat; background-size: 100%; } } utils.service.ts//utils.service.ts import { Injectable,EventEmitter } from '@angular/core'; @Injectable() export class UtilsService { public toastChange: EventEmitter<any>; toast(data) { this.toastChange.emit(data); } } 注册组件与服务import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { UtilsService } from './utils.service'; import { ToastComponent } from './toast.component.ts'; @NgModule({ imports: [ CommonModule ],declarations: [ ToastComponent ],providers: [UtilsService],}) export class AppModule { } 使用//app.component.html <app-toast></app-toast> 天之骄子 2017.8.15 星期二 深圳 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |