角度材料创建类似于引导警报的警报

时间:2017-06-13 15:58:28

标签: angularjs angular-material

我是角质材料的新手。我正在尝试使用角度材料来实现警报以显示消息,这在引导警报中是相似的,即。

<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>

任何人都可以帮助我在角材料中实施最佳方法吗?

非常感谢

2 个答案:

答案 0 :(得分:8)

Angular材料没有内置的Alert组件,但是您可以非常容易地实现和自定义它,此实现包括一个组件和一个服务,模板和CSS文件完成了这些组成。

警报组件

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();
        }
    }

警报模板

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

警报样式

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

警报服务

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();
    }
}

典型用法

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

在登录失败时显示警报的用法示例

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

答案 1 :(得分:0)

您可以利用* ng的优势,如果要显示更多,则只需简单的字符串,如下所示:

showMsg: boolean = false;

onSubmit() {
this.userService.createUser(this.addForm.value)
  .subscribe( data => {
    this.router.navigate(['list-user']);
    this.showMsg= true;
  });
}
then you can use showMsg boolean to show/hide dive like below

<div class="col-md-6">
  <div ng-click=="onSubmit()">

   <div class="row"  *ngIf="showMsg">
      <div class="col-xs-12">
         <p class="alert alert-success">
             <strong>Registration Success!</strong> Please click here to login!.

         </p>
      </div>
    </div>

    <button class="btn btn-success">Add user</button>
  </div>
</div>

请注意,我正在使用一些引导程序类进行样式设计。