1

I have created a custom button component and I am using it in one of templates. I want to disable this button component using disabled property when the form is invalid. How do I achieve this? which Angular API I can use? For instance: In html i am using "app-okbutton" component "I want to use disable property like this [disabled]="??" in app-okbutton Image for reference https://i.sstatic.net/C3xdR.png

Link to my repo for reference https://github.com/hemantmali21/Angular2-Demo/blob/master/src/app/okbutton/okbutton.component.ts

Thanks in Advance.

3

1 Answer 1

1
@Component({
  selector: 'app-okbutton',
  template: `
  <button [disabled]="disabled"
    [type]= "type" class="btn btn-primary {{className}}" (click)="onClickEvent.emit($event)">
          Save
  </button>
  `,
  styleUrls: []
})
export class OkbuttonComponent {
  @Input() className = ''; // default value if none is passed
  @Input() type = 'button'; // default value if none is passed
  @Input() disabled = false; // default value if none is passed
  @Output() onClickEvent: EventEmitter<any> = new EventEmitter<any>();
}

And then you can use it as follows (with a form for example):

<form #form="ngForm" novalidate>
// form fields go here
</form>
<app-okbutton [disabled]="!form.valid"></app-okbutton>
Sign up to request clarification or add additional context in comments.

1 Comment

It would be nice to be able to use the native (click) event on the component. But if you do <app-okbutton (click)="foo()"> it seems the component can't stop the click event from firing if it's disabled. Is there a way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.