角材料创建类似于引导程序警报的警报 [英] Angular material create alert similar to bootstrap alerts

查看:22
本文介绍了角材料创建类似于引导程序警报的警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是角材料的新手.我正在尝试使用与引导程序警报类似的角度材料来实现警报以显示消息,即.

<div class="alert alert-info" role="alert"><strong>注意!</strong>此警报需要您注意,但它并不重要.

<div class="alert alert-warning" role="alert"><strong>警告!</strong>最好检查一下自己,你看起来不太好.

<div class="alert alert-danger" role="alert"><strong>哦,啪!</strong>更改一些内容,然后再次尝试提交.

谁能帮助我在角材料中实现的最佳方法是什么?

非常感谢

解决方案

Angular materials 没有内置的 Alert Component 但是你可以很容易的实现并自定义它,这个实现包括一个组件和一个服务,模板和 css 文件完成这些作文.

警报组件

import { Component, OnInit, OnDestroy } from '@angular/core';从'rxjs'导入{订阅};从 'src/app/_services' 导入 { AlertService };@成分({选择器:'警报',templateUrl: 'alert.component.html',styleUrls: ['./alert.component.css']})导出类 AlertComponent 实现 OnInit、OnDestroy {私人订阅:订阅;消息:任何;构造函数(私有警报服务:警报服务){}ngOnInit() {this.subscription = this.alertService.getMessage().subscribe(message => {this.message = 消息;});}ngOnDestroy() {this.subscription.unsubscribe();}}

<小时>

警报模板

<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === '错误' }">{{message.text}}</div>

<小时>

警报样式

.alert-danger {背景颜色:#f44336;/* 红色的 */}.警报成功{背景颜色:#36f456;}.警报{填充:20px;白颜色;底边距:15px;文本对齐:居中;}

<小时>

警报服务

import { Injectable } from '@angular/core';从@angular/router"导入{路由器,导航开始};从 'rxjs' 导入 { Observable, Subject };@Injectable()导出类 AlertService {私人主题 = 新主题<任何>();私人 keepAfterNavigationChange = false;构造函数(私有路由器:路由器){//清除路由更改的警报消息this.router.events.subscribe(event => {如果(导航开始的事件实例){如果(this.keepAfterNavigationChange){//只保留一个位置变化this.keepAfterNavigationChange = false;} 别的 {//清除警报this.subject.next();}}});}成功(消息:字符串,keepAfterNavigationChange = false){this.keepAfterNavigationChange = keepAfterNavigationChange;this.subject.next({ type: 'success', text: message });}错误(消息:字符串,keepAfterNavigationChange = false){this.keepAfterNavigationChange = keepAfterNavigationChange;this.subject.next({ type: 'error', text: message });}getMessage(): Observable{返回 this.subject.asObservable();}}

<小时>

典型用法

this.alertService.error("错误!!出了点问题");this.alertService.success("成功,你完成了");

登录失败提示使用示例

onSubmit(){this.authService.login(this.user).subscribe((res: 任何) =>{if(!res.hasError && res.token){this.authService.isLoggedIn = true;localStorage.setItem('token', res.token);this.router.navigate(['/']);} 别的 {this.alertService.error(res.errorMessage);}},错误 =>{this.alertService.error(err.errorMessage);});}

I am new to angular material. i am trying to implement alert to display messages using angular material which is similar in bootstrap alert ie.

<div class="alert alert-success" role="alert">
  <strong>Well done!</strong> You successfully read this important alert message.
</div>
<div class="alert alert-info" role="alert">
  <strong>Heads up!</strong> This alert needs your attention, but it's not super important.
</div>
<div class="alert alert-warning" role="alert">
  <strong>Warning!</strong> Better check yourself, you're not looking too good.
</div>
<div class="alert alert-danger" role="alert">
  <strong>Oh snap!</strong> Change a few things up and try submitting again.
</div>

Can anyone help me what is the best way to implement in angular material?

Many Thanks

解决方案

Angular materials Doesnot Have built-in Alert Component but you can implement one very easy and customize it ,This implementation includes one component and one service which template and css file complete these composition .

Alert Component

import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs';
    import { AlertService } from 'src/app/_services';

    @Component({
        selector: 'alert',
        templateUrl: 'alert.component.html',
        styleUrls: ['./alert.component.css']
    })

    export class AlertComponent implements OnInit, OnDestroy {
        private subscription: Subscription;
        message: any;

        constructor(private alertService: AlertService) { }

        ngOnInit() {
            this.subscription = this.alertService.getMessage().subscribe(message => { 
                this.message = message; 
            });
        }

        ngOnDestroy() {
            this.subscription.unsubscribe();
        }
    }


Alert Template

<div *ngIf="message" [ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">{{message.text}}</div>


Alert Style

.alert-danger {
    background-color: #f44336; /* Red */
}
.alert-success {
    background-color: #36f456;  
} 
.alert{
    padding: 20px;
    color: white;
    margin-bottom: 15px;
    text-align: center;
}


Alert Service

import { Injectable } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
import { Observable, Subject } from 'rxjs';

@Injectable()
export class AlertService {
    private subject = new Subject<any>();
    private keepAfterNavigationChange = false;

    constructor(private router: Router) {
        // clear alert message on route change
        this.router.events.subscribe(event => {
            if (event instanceof NavigationStart) {
                if (this.keepAfterNavigationChange) {
                    // only keep for a single location change
                    this.keepAfterNavigationChange = false;
                } else {
                    // clear alert
                    this.subject.next();
                }
            }
        });
    }

    success(message: string, keepAfterNavigationChange = false) {
        this.keepAfterNavigationChange = keepAfterNavigationChange;
        this.subject.next({ type: 'success', text: message });
    }

    error(message: string, keepAfterNavigationChange = false) {
        this.keepAfterNavigationChange = keepAfterNavigationChange;
        this.subject.next({ type: 'error', text: message });
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}


Typical usages

this.alertService.error("Error!! Something went wrong");
this.alertService.success("Success, You are done");

Usage Example Which Displays Alert on Login Failure

onSubmit(){
      this.authService.login(this.user).subscribe(

        (res: any) => {
          if(!res.hasError && res.token){
            this.authService.isLoggedIn = true;
            localStorage.setItem('token', res.token); 
            this.router.navigate(['/']);
          } else {
            this.alertService.error(res.errorMessage);
          }

        },
        err => {
          this.alertService.error(err.errorMessage);
        }
      );     
    }

这篇关于角材料创建类似于引导程序警报的警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆