在模板中我们需要添加隐藏/显示按钮并对其进行操作。解决方法如下所示:
1.模板:
2.组件:
import { Component } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({ selector: 'app-password', templateUrl: './password.component.html', styleUrls: ['./password.component.css'] }) export class PasswordComponent { hidePassword = true; // initial value for hidePassword
form = new FormGroup({ password1: new FormControl('', [Validators.required, Validators.minLength(6)]), password2: new FormControl('', [Validators.required, Validators.minLength(6)]) });
hideUnhide() { this.hidePassword = !this.hidePassword; // toggle hidePassword }
get password2Type() { return this.hidePassword ? 'password' : 'text'; // determine input type based on hidePassword } }
这里使用了一个新的getter方法 password2Type 来根据 hidePassword的状态(true或false)来切换第二个密码框的input类型。
在按钮的点击事件方法中,使用 ! 操作符将 hidePassword 改为相反的值, 这样就可以动态地切换输入密码时的显示和隐藏了。