【问题标题】:Conditionally rendering message on HTML page from Typescript in runtime [Angular]在运行时从 Typescript 有条件地在 HTML 页面上呈现消息 [Angular]
【发布时间】:2020-02-09 08:12:09
【问题描述】:

我是 Angular 的新手。所以我可能无法正确地提出问题。我提前道歉。我也试过this 问题。我为我的MEAN stack 应用程序创建了一个登录表单。这是一个使用emailpassword 字段的简单登录。我的打字稿文件决定登录是否成功。这是我的代码。

login.component.ts

import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
...

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  flag= {
    valid: true
  }

  ...

  constructor( private _auth: AuthService, private _router: Router) {
  }

  ngOnInit() {
  }


  onSubmit() {
    this._auth.loginUser(this.loginUserData)
    .subscribe(
      res => {
        ...
      },
      err => {
        this.flag.valid=false,
        document.querySelector('#login-denied').innerHTML="hello";
      }
    )
  }
}

在上述文件中,flag 是一个布尔变量。 True 表示值正常,否则为 False。

这是我的 html 代码 login.component.html

<form>
  <div class="form-group">
      USERNAME FIELD
  </div>

  <div class="form-group">
      PASSWORD FIELD
  </div>
  <button type="submit" (click)="onSubmit()">Submit</button>

  <span *ngIf="flag.valid===false" id="login-denied">
      <i class="fa fa-times-circle" style="color:firebrick;"></i>
  </span>
</form>

请多多关注我的span 标签。请纠正我。我得到了

“document.querySelector(...) 为空”

这里还有一个

如您所见。 fa 图标在那里。但没有消息。

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    在你的登录组件中添加一个字符串属性“message”

    export class LoginComponent implements OnInit {
      message: string = '';
      …
    }
    

    在您的提交方法中

    onSubmit() {
      this._auth.loginUser(this.loginUserData)
      .subscribe(
        res => {
          ...
        },
        err => {
          this.flag.valid=false,
          this.message = "hello";
        }
      )
    }
    

    在你的 html 中

    <span *ngIf="!flag.valid" id="login-denied">
      <i class="fa fa-times-circle" style="color:firebrick;">{{message}}</i>
    </span>
    

    问候

    【讨论】:

    • 不建议直接在 Angular 中访问 DOM,因为您正在绕过 Angular 渲染器。这可能会产生不希望的和不可预测的结果。
    【解决方案2】:

    为什么你需要这样做

    document.querySelector
    

    因为你可以用一个变量来做,一个角度的变量会更合适

     error message="";
    // When error occurred set the message variable
    

    在误差函数中这样

    err => {
            this.flag.valid=false;
    this.errorMessage ="Some Error";
            }
    
    

    并像这样在html中绑定它

    <span *ngIf="flag.valid===false" id="login-denied">
          <i class="fa fa-times-circle" style="color:firebrick;"></i> {{errorMessage}}
      </span>
    
    

    【讨论】:

    • 我在互联网的某个地方看到了这种方法,它对他们有用。
    猜你喜欢
    • 2015-09-18
    • 2021-06-04
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2019-12-22
    相关资源
    最近更新 更多