Reputation: 548
I have an application in Angular in which I have a checkbox that requires authentication before it changes. The idea here is as follows:
I tried using preventDefault
with both the click
and change
events. It prevents the change, but it doesn't allow me to set it dynamically. I also tried the following:
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>
Typescript:
@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;
}
}
Upvotes: 1
Views: 577
Reputation: 2710
Checkboxes are a little tricky. You need to change its checked
property
HTML
<input id="authenticate" type="checkbox" #checkbox (change)="CheckForAuthentication(checkbox)" />
Typescript
@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;
}
}
I used a template variable but this can also be done with @ViewChild
Upvotes: 1