首页 > 解决方案 > Angular 9 - 基于身份验证更改复选框值

问题描述

我在 Angular 中有一个应用程序,其中有一个复选框,需要在更改之前进行身份验证。这里的思路如下:

我尝试preventDefault同时使用clickchange事件。它可以防止更改,但不允许我动态设置它。我还尝试了以下方法:

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;
    }
}

标签: angular

解决方案


复选框有点棘手。你需要改变它的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


推荐阅读