angular - *ngIf 不对 bool 值变化使用react

标签 angular angular2-directives angular-directive

这里有一些代码。同样的模式(afaik)适用于英雄教程。

login.component.html:

<div class="four wide column middle aligned" *ngIf="wrongCredentialsInserted">
     <div class="ui error message">Invalid credentials
     </div>
 </div>

login.component.ts:
wrongCredentialsInserted: boolean = false;

//...      

onSubmit(login: LoginDto): void {
        console.log(`User '${login.username}' attempts to login...`);
        if (this.authService.login(login.username, login.password)) {
          this.location.back();
        } else {
          this.wrongCredentialsInserted = true; //This line gets executed!
        }
      }

即使我设置了 wrongCredentialsInserted,消息也不会显示为真。它设置为 true,我已经验证了这一点。我也尝试过 *ngIf="wrongCredentialsInserted === true" ,因为我在其他地方读过,但它没有用。
我读到这可能与“从 Angular 2 开始的单向数据流”有关,但我知道我们能够在我们公司的 A2+ 项目中做这些事情。 AFAIK 一种方式的数据绑定(bind)仅指组件-组件通信。

任何形式的帮助都将受到高度赞赏。

编辑:由于我所做的事情似乎有些困惑,因此我将整个文件发布在这里。

login.component.ts
import {AbstractControl, FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {routerTransition} from '../../router.transition';
import {Component} from '@angular/core';
import {AuthService} from '../auth.service';
import {LoginDto} from './login-dto';
import {Location} from '@angular/common';

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

  private readonly USERNAME: string = 'username';
  private readonly PASSWORD: string = 'password';

  myForm: FormGroup;
  username: AbstractControl;
  password: AbstractControl;

  message: string;
  wrongCredentialsInserted = false;

  constructor(public fb: FormBuilder,
              public authService: AuthService,
              public location: Location) {
    this.message = '';

    this.myForm = fb.group({
      username: ['', Validators.required],
      password: ['', Validators.required]
    });

    this.username = this.myForm.controls[this.USERNAME];
    this.password = this.myForm.controls[this.PASSWORD];
  }

  onSubmit(login: LoginDto): void {
    console.log(`User '${login.username}' attempts to login...`);
    if (this.authService.login(login.username, login.password)) {
      this.location.back();
    } else {
      this.wrongCredentialsInserted = true;
    }
  }

  login(username: string, password: string): boolean {
    this.message = '';
    if (!this.authService.login(username, password)) {
      this.message = 'Incorrect credentials.';
      setTimeout(
        function () {
          this.message = '';
        }.bind(this), 2500);
    }
    return false;
  }

  logout(): boolean {
    this.authService.logout();
    return false;
  }

}

login.component.html
<div class="ui raised segment">
  <form [formGroup]="myForm"
        (ngSubmit)="onSubmit(myForm.value)"
        class="ui form"
        [class.error]="!myForm.valid">

    <div class="field"
         [class.error]="!username.valid && username.touched">
      <label for="username">Username:</label>
      <input type="text"
             id="username"
             placeholder="Username"
             [formControl]="username">
      <div *ngIf="username.hasError('required') && username.touched"
           class="ui error message">
        Username is required
      </div>
    </div>

    <div class="field"
         [class.error]="!password.valid && username.touched">
      <label for="password">Password:</label>
      <input type="text"
             id="password"
             placeholder="Password"
             [formControl]="password">
      <div *ngIf="password.hasError('required') && password.touched"
           class="ui error message">Password is required
      </div>
    </div>

    <div class="ui grid">

      <div class="two wide column middle aligned">
        <button type="submit"
        class="ui button"
        [class.disabled]="!myForm.valid">Submit
        </button>
      </div>

      <div class="fourteen wide column middle aligned" *ngIf="wrongCredentialsInserted">
        <div
          class="ui error message">Invalid credentials
          </div>
        </div>

      </div>

    </form>
  </div>

login.component.css:空

auth.service.ts:
@Injectable()
export class AuthService {

  constructor(private http: Http) {
  }

  login(user: string, password: string): boolean {
    if (user === 'user' && password === 'password') {
      localStorage.setItem('username', user);
      return true;
    }

    return false;
  }

  logout(): any {
    localStorage.removeItem('username');
  }

  getUser(): any {
    return localStorage.getItem('username');
  }

  isLoggedIn(): boolean {
    console.log(`Is user logged in? ' + ${this.getUser() !== null}`);
    return this.getUser() !== null;
  }
}

最佳答案

*ngIf 有几个可能的原因对模型的变化没有反应。

更改检测未运行

您正在使用 OnPush您的组件上的策略并更改组件状态,而无需手动触发 CD 循环。要么重新打开自动 CD,要么通过注入(inject) ChangeDetectorRef 手动触发 CD。并使用适合您需要的方法。

风格会误导你

有可能ngIf绑定(bind)工作正常,并且模板被正确创建和销毁,但是有些样式在视觉上会掩盖这一点,例如 display: none , visibility: hidden等。确保通过打开浏览器的开发工具检查页面。

有一个 Uncaught Error

如果您在开发时没有打开控制台,很容易错过。可能有一个错误破坏了你的代码,Angular 无法从中恢复;从而防止任何进一步的 CD 循环运行和更新 DOM。确保有一个打开的控制台来检查错误。

你甚至没有改变模型

Angular 是一个框架,您可以在其中声明性地指定您希望如何基于模型创建 DOM。您可以通过编写模板来做到这一点。如果你的模型没有改变,DOM 也不会改变。确保正确的代码段正在运行。一个快速的方法是放置一个 console.log在更改变量的代码附近。您还可以在浏览器的开发工具中放置断点,或使用 Chrome 的实用程序扩展,例如 Augury独立于基于模板呈现的方式检查模型。

关于angular - *ngIf 不对 bool 值变化使用react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388831/

相关文章:

angular - 如何从父组件重置子组件中的字段 - Angular

javascript - Angular2+ : how does NgModel/NgControl internally handle updates from view to model?

angular - 使用@ContentChildren() 访问每个 ng-template 名称

html - ionic 2 : Dismiss loading animation when iframe is ready

angular - PrimeNG 日历错误 - 未定义 JQuery

angular - Angular2 中的自定义值访问器

javascript - 如何访问 Angular 组件 $postLink 内的元素

Angular2根据字符串数组过滤对象数组

javascript - Ionic2:当你来到页面时,你如何选择要关注的输入?

javascript - 将指令属性添加到指令元素