【问题标题】:Error - How to dynamic show/hide alert in Angular 2 based on authentication错误 - 如何基于身份验证在 Angular 2 中动态显示/隐藏警报
【发布时间】:2017-01-26 18:22:18
【问题描述】:

我在几秒钟内显示/隐藏警报元素时遇到问题。当我未通过身份验证时,我想在几秒钟内隐藏警报危险,当我通过身份验证时,我想在几秒钟内动态显示警报成功并隐藏警报危险。

有可能吗? 我用 jQuery 做的,它以一种方式工作并给我错误。

警告消失时控制台显示的错误是:

TypeError: Cannot read property 'nativeElement' of undefined
    at HTMLDivElement.<anonymous> (app.component.ts:19)
    at HTMLDivElement.e.complete (jquery.min.js:3)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at i (jquery.min.js:3)
    at Function.r.fx.tick (jquery.min.js:3)
    at bb (jquery.min.js:3)
    at ZoneDelegate.invokeTask (zone.js:265)
    at Object.onInvokeTask (ng_zone.js:227)
    at ZoneDelegate.invokeTask (zone.js:264)

应用组件 ts 文件

import { Component, ElementRef, AfterViewInit } from '@angular/core';
import { Auth } from './auth.service';

declare var jQuery: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements AfterViewInit {


  constructor(private auth: Auth,
              private elementRef: ElementRef) {}

  ngAfterViewInit() {
    if (!this.auth.authenticated()) {
    jQuery(this.elementRef.nativeElement).find('#loggedOut').fadeTo(3000, 1000).slideUp(1000, function(){
    jQuery(this.elementRef.nativeElement).find('#loggedOut').slideUp(1000);
      });
    } else if (this.auth.authenticated()) {
    jQuery(this.elementRef.nativeElement).find('#loggedIn').fadeTo(3000, 1000).slideUp(1000, function(){
    jQuery(this.elementRef.nativeElement).find('#loggedIn').slideUp(1000);
      });
    }
  }

}

应用组件html文件

<app-header></app-header>
<div class="container">
    <div class="alert alert-success alert-dismissable" id="loggedIn" *ngIf="auth.authenticated()">You are logged in</div>
<div class="alert alert-danger alert-dismissable" id="loggedOut" *ngIf="!auth.authenticated()">You are not logged in</div>
    <router-outlet></router-outlet>
</div>

This is app.component.html

This is app.component.ts

【问题讨论】:

  • ngIf 为 false 时根本不会在页面上渲染组件,因此您的 jquery 将无法找到它。

标签: jquery angular angular-ng-if


【解决方案1】:

我认为您可以直接搜索 id 为“LoggedIn”或“LoggedOut”的元素,但正如 Jonathan Niu 所说,ngIf 会完全从 DOM 中消除它们,因此您可以将 id 移至父级

<div class="container" id="LoggedIn">

并应用您的动画

【讨论】:

    猜你喜欢
    • 2018-05-01
    • 2020-06-03
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多