【问题标题】:*ngIf not working as expected*ngIf 没有按预期工作
【发布时间】:2023-03-07 11:57:02
【问题描述】:

如何使以下工作正常工作?它总是返回一个真条件(即,即使密码 1 和密码 2 相同,也总是显示错误)。

<div *ngIf="password2 != password1 && password2.touched" class="error-box">* Passwords must match!</div>

谢谢

整个html

<ion-content padding>
    <form [ngFormModel]="authForm" (ngSubmit)="onSubmit(authForm.value)">
        <ion-item [class.error]="!username.valid && username.touched">
            <ion-label floating>Username</ion-label>
            <ion-input type="text" value="" [(ngFormControl)]="username"></ion-input>
        </ion-item>
        <div *ngIf="username.hasError('required') && username.touched" class="error-box">* Username is required!</div>
        <div *ngIf="username.hasError('minlength') && username.touched" class="error-box">* Minimum username length is 3!</div>
        <div *ngIf="username.hasError('maxlength') && username.touched" class="error-box">* Maximum username length is 25!</div>
        <div *ngIf="username.hasError('checkFirstCharacterValidator') && username.touched" class="error-box">* Username cant't start with number!</div>

        <ion-item [class.error]="!password1.valid && password1.touched">
            <ion-label floating>Password</ion-label>
            <ion-input type="password" value="" [(ngFormControl)]="password1"></ion-input>
        </ion-item>
        <div *ngIf="password1.hasError('required') && password1.touched" class="error-box">* Password is required</div>
        <div *ngIf="password1.hasError('minlength') && password1.touched" class="error-box">* Minimum password length is 6!</div>
        <div *ngIf="password1.hasError('maxlength') && password1.touched" class="error-box">* Maximum password length is 25!</div>

        <ion-item [class.error]="!password2.valid && password2.touched">
            <ion-label floating>Confirm Password</ion-label>
            <ion-input type="password" value="" [(ngFormControl)]="password2"></ion-input>
        </ion-item>
        <div *ngIf="password2.hasError('required') && password2.touched" class="error-box">* Password is required</div>
        <div *ngIf="password2.hasError('minlength') && password2.touched" class="error-box">* Minimum password length is 6!</div>
        <div *ngIf="password2.hasError('maxlength') && password2.touched" class="error-box">* Maximum password length is 25!</div>
        <div *ngIf="password2 != password1 && password2.touched" class="error-box">* Passwords must match!</div>

        <br/><br/>
        <button type="submit" primary [disabled]="!authForm.valid" block class="form-button-text">Next</button>
    </form>
</ion-content>

ts

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, AbstractControl} from '@angular/common';
import {Validator} from '../validator/validator';
import {CategoryPage} from '../category/category';
import { EmployeeModel } from '../model/EmployeeModel';

@Component({
  templateUrl: 'build/pages/register/register.html',
  directives: [FORM_DIRECTIVES]
})

export class RegisterPage {

  authForm: ControlGroup;
  username: AbstractControl;
  password1: AbstractControl;
  password2: AbstractControl;
  passwordGroup: AbstractControl;

  constructor(private nav: NavController, private fb: FormBuilder, private employeeModel: EmployeeModel) {
    this.authForm = fb.group({
      'username': ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.required, Validators.maxLength(25), Validator.checkFirstCharacterValidator])],
      'password1': ['', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(25)])],
      'password2': ['', Validators.compose([Validators.required, Validators.minLength(6)])],
    });

    this.username = this.authForm.controls['username'];
    this.password1 = this.authForm.controls['password1'];
    this.password2 = this.authForm.controls['password2'];
  }

【问题讨论】:

  • 我从未见过像这样使用* 的符号。但如果不是ng-if="password2 != password1 &amp;&amp; password2.touched" - 我还注意到上面代码中的第二个* 在在 HTML 中关闭 &gt;,对吗?
  • 这是角度 2 吗?
  • @NicholasRobinson 这是语法完全不同的角度 2。
  • 我使用的是 Angular 2 之上的 Ionic 2

标签: javascript html angular


【解决方案1】:

尝试将双向数据绑定添加到您的密码输入中,如下所示:

[(ngFormControl)]="password1"

顺便说一下,ngFormControl 和 ngFormModel 现已弃用。

这是一个工作示例:(这真的很简单,我只是想测试 *ngIf 指令是否有效):

ma​​in.ts

import { bootstrap }    from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { disableDeprecatedForms, provideForms } from '@angular/forms'
bootstrap(AppComponent, [
disableDeprecatedForms(),
provideForms()
]);

app.component.ts

import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
})
export class AppComponent {
name: string = "";
pass1: string = "";
pass2: string = "";
onSubmitLogin() {
    console.log("LOGIN!");
}
}

app.component.html

<form #loginForm="ngForm" (ngSubmit)="onSubmitLogin()">
<label for="name">Username:</label>
<input type="text" [(ngModel)]="name" name="name" required />
<label for="pass1">Password:</label>
<input type="password" [(ngModel)]="pass1" name="pass1" required />
<label for="pass2">Confirm password:</label>
<input type="password" [(ngModel)]="pass2" name="pass2" required />
<button type="submit" class="btn btn-primary">Submit</button>

<div *ngIf="pass1 != pass2" align="center">
    PASSWORDS ARE NOT THE SAME
</div>
</form>

index.html

<html>
<head>
<script>document.write('<base href="' + document.location + '" />');</script>
<title>Angular 2 Tour of Heroes</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 1. Load libraries -->
 <!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="systemjs.config.js"></script>
<script>
  System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>

【讨论】:

  • 您好 Stefan,感谢您的建议。如果 ngFormControlngFormModel 被贬低,我应该改用什么?谢谢
  • 对于您的表单标签,您应该使用#yourFormName="ngForm",在您的输入标签中您应该使用[(ngModel)]="password1"
  • 添加括号使其成为[(ngFormControl)]="password1" 没有区别。
  • 您还应该添加[(ngFormControl)]="password2"。您的 component.ts 文件中是否有名称为 password1 和 password2 的字符串类型变量?你没有添加你的 .ts 文件,所以我不能说。
  • 我现在已将 ts 文件添加到原始问题中...如您所见,我现在确实有 [(ngFormControl)]="password2",但结果没有变化。
猜你喜欢
  • 2018-09-12
  • 2016-10-30
  • 2018-05-29
  • 1970-01-01
  • 2021-10-19
  • 2020-03-18
  • 2012-06-14
  • 2014-11-15
  • 1970-01-01
相关资源
最近更新 更多