简体   繁体   中英

How to enable or disable the submit button thru radio button in angular

here's the code:

list.component.html

<nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)">
              <label nz-radio nzValue="passed">Passed</label>
              <label nz-radio nzValue="failed">Failed</label>
            </nz-radio-group>
<button class="mr-1" nz-button nzType="primary" type="button" [disabled]="disableSubmitBtn()">
  <span translate>Submit</span>
</button>

When it select the passed it should enabled the submit button if it select the failed it should disabled the submit button

just a small change in your code

<nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)">
          <label nz-radio nzValue="passed">Passed</label>
          <label nz-radio nzValue="failed">Failed</label>
        </nz-radio-group>
<button class="mr-1" nz-button nzType="primary" type="button" [disabled]="radioValue == 'failed'">
    <span translate>Submit</span>
</button>

您只需更改以下行

 <button class="mr-1" nz-button nzType="primary" type="button" [disabled]="!radioValue ? 'disabled': null">

You can try like this

<nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)">
              <label nz-radio nzValue="passed">Passed</label>
              <label nz-radio nzValue="failed">Failed</label>
            </nz-radio-group>
<button class="mr-1" nz-button nzType="primary" type="button" [disabled]="radioValue == 'passed' ? 'false' : 'true'">
  <span translate>Submit</span>
</button>

You may asssign true or false value to radio button to identify pass or fail. And use this condition to enable or disable button.

<nz-radio-group formControlName="radiostatus" [(ngModel)]="radioValue" (ngModelChange)="onChangeStatus($event)">
              <label nz-radio nzValue="true">Passed</label>
              <label nz-radio nzValue="false">Failed</label>
            </nz-radio-group>
<button class="mr-1" nz-button nzType="primary" type="button" [disabled]="nzValue" >
  <span translate>Submit</span>
</button>

The best and efficient way to achieve this is to use custom validators in angular forms.

import { ValidationErrors, AbstractControl } from '@angular/forms';

export class CustomValidator{
    static checkIfPassed (control: AbstractControl): ValidationErrors | null {
        if (control.value == 'passed') {
            return { shouldbepassed: true }
        }
        return null;
    }
}

Then use this validator in you angular forms.

passed: ['', [Validators.required, checkIfPassed]],
failed: ['', [Validators.required, checkIfPassed]],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM