angular - Angular 9 - 基于身份验证更改复选框值
问题描述
我在 Angular 中有一个应用程序,其中有一个复选框,需要在更改之前进行身份验证。这里的思路如下:
- 该复选框未选中。
- 用户单击复选框。
- 用户需要输入身份验证详细信息。
- 如果身份验证成功,复选框将被选中。
- 如果身份验证不成功,则该复选框保持未选中状态。
我尝试preventDefault
同时使用click
和change
事件。它可以防止更改,但不允许我动态设置它。我还尝试了以下方法:
HTML:
<div class="pull-right">
<input id="authenticate" type="checkbox" [(ngModel)]="IsAuthenticated" (ngModelChange)="CheckForAuthentication($event)"/>
<label class="label" for="authenticate">
<span>Authenticate</span>
</label>
</div>
打字稿:
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.scss']
})
export class AuthenticationComponent implements OnInit {
IsAuthenticated: boolean = false;
constructor(protected service: AuthenticationService) {}
ngOnInit() {}
async CheckForAuthentication(value: boolean) {
// If we're unchecking don't do anything
if (!value) {
return;
}
// Remain false until authentication is complete
this.IsAuthenticated = false;
// Wait for authentication
const authenticated = await this.service.Authenticate();
// If authentication is true, change the checkbox
this.IsAuthenticated = authenticated;
}
}
解决方案
复选框有点棘手。你需要改变它的checked
属性
HTML
<input id="authenticate" type="checkbox" #checkbox (change)="CheckForAuthentication(checkbox)" />
打字稿
@Component({
selector: 'app-authentication',
templateUrl: './authentication.component.html',
styleUrls: ['./authentication.component.scss']
})
export class AuthenticationComponent implements OnInit {
constructor(protected service: AuthenticationService) { }
private IsAuthenticated: boolean = false;
ngOnInit() { }
async CheckForAuthentication(checkbox: HTMLInputElement) {
// If we're unchecking don't do anything
if (!checkbox.checked) {
return;
}
// Remain false until authentication is complete
this.IsAuthenticated = false;
checkbox.checked = false;
// Wait for authentication
const authenticated = await this.service.Authenticate();
// If authentication is true, change the checkbox
this.IsAuthenticated = authenticated;
checkbox.checked = authenticated;
}
}
我使用了一个模板变量,但这也可以用@ViewChild
推荐阅读
- ios - UICollectionView 未显示正确数量的项目
- angular - 使用 Angular 8 为嵌套对象创建模态的良好做法是什么
- activemq-artemis - 更改 ActiveMQ Artemis 消息的时间戳
- c++ - 链接第三个库时如何理解段错误的原因?
- arduino - 薄膜键盘输入的字符分配不正确
- opencv - 检测测试卡带上的线条 opencv
- azure - Azure FHIR 代理 - 无法通过 Postman 访问
- perl - 最后一个字符串出现在格式化输出的行首
- bash - Bash - 如何在 if [] 条件内设置变量并在外部使用
- javascript - 大量文本行之间的间距 css/html/js