Formarray验证并禁用下一个按钮angular4

时间:2017-10-10 11:14:23

标签: html angular typescript

我想验证angular4中的复选框。就像我有两个复选框,我通过反应形式使用formarray生成,如果没有选中,我需要禁用我的下一个按钮。

感谢您的帮助

totalAccounts = [
        {numOfAccounts:1, id:1, accountName:"CHECKING ACCOUNT - ACCOUNT 1"}, 
        {numOfAccounts:1, id:2, accountName:"MONEY MARKET ACCOUNT - ACCOUNT 2"}
    ];

let accountsArray = [];
        for (let account of this.totalAccounts) {
            accountsArray.push(this.formBuild.group({
            isChosen: [true, Validators.required],
            numOfAccounts:[account.numOfAccounts, Validators.required],
            accountName: [account.accountName, Validators.required],
            id:account.id,
            accountValueText: "Number of accounts to open:",
          }));
        } 
        this.accountSetup = this.formBuild.group({
            accountList: this.formBuild.array(accountsArray)
        });
<form *ngIf="accountSetup" [formGroup]="accountSetup" novalidate (ngSubmit)="onSubmit()">
    <div class="row">
        <section class="page col-sm-12">
            <div class="form-group" style="padding:3%;" formArrayName="accountList">
                <div *ngFor="let account of accountList.controls; let i=index" [formGroupName]="i">
                    <label class="checkbox-inline citi-checkbox" style="font-family: 'Interstate', sans-serif; font-size: 20px">
                        <input type="checkbox" formControlName="isChosen" (click)="checked()" /> {{account.controls.accountName.value}}   
                    </label>
                    <br>
                    <p style="padding-left:22px;">
                            {{account.controls.accountValueText.value}}
                        <input class="form-control" formControlName="numOfAccounts" placeholder="Enter" style="width:100px;">
                    </p><br>
                </div>
            </div>
        </section>
    </div>
    <div class="row">
        <section class="page col-sm-12">
            <div class="row">
                <nav aria-label="...">
                    <ul class="pager">
                        <button type="button" class="previous" (click)="goToPreviousPage()">Previous</button>
                        <button type="submit" class="next" [disabled]="accountSetup.invalid">Next</button>
                    </ul>
                </nav>
            </div>
            
        </section>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

作为快速修复,您可以在totalAccounts上设置新字段,并在点击次数上设置其值。如果它们为假,则将按钮设置为禁用。

totalAccounts = [
        {numOfAccounts:1, id:1, accountName:"CHECKING ACCOUNT - ACCOUNT 1", checked: false}, 
        {numOfAccounts:1, id:2, accountName:"MONEY MARKET ACCOUNT - ACCOUNT 2", checked: false}
]

HTML

    <input type="checkbox" #check formControlName="isChosen" (click)="checked(); totalAccounts[i]=!totalAccounts[i]" /> {{account.controls.accountName.value}}   
......

    <button type="submit" class="next" [disabled]="!(totalAccounts[0] && totalAccounts[1])">Next</button>