首页 > 解决方案 > Angular4 - 取消选中复选框

问题描述

我想在取消选中复选框时打开确认,在单击取消时我想选中复选框。

HTML:

<div class="form-group col-xs-1">
    <input type="checkbox" name="add" (change)="test()"
        [(ngModel)]="add.checked" />{{add.name}}
</div>

打字稿:

import { Component} from '@angular/core';
@Component({
    selector: 'test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})
export class TestComponent {
    add: any = { name: 'Laptops', checked: true };
    constructor() { }
    test() {
        if (!this.add.checked) {
            this.add.checked = !confirm('Are you sure?');
        }
    }
}

请帮忙

标签: angular

解决方案


我通过使用 setTimeout 找到了自己的答案:

import { Component} from '@angular/core';
@Component({
    selector: 'test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css']
})
export class TestComponent {
    add: any = { name: 'Laptops', checked: true };
    constructor() { }
    test() {
        if (!this.add.checked) {
            let confirm = !confirm('Are you sure?');
            setTimeout(() => {
                this.add.checked = confirm;
            }, 0);       
        }
    }
}

推荐阅读