compliance
compliance

Reputation: 434

How to set disabled button property using a function?

I'm trying:

Maximilian instructor used a constructor. But I want to use a function instead, so I wrote below function but it's not working (the button is always enabled).

servers.component.ts:

export class ServersComponent implements OnInit {

  allowNewServer = false;

  AllowNewServerFunction(){
    setTimeout(()=>{
      return this.allowNewServer = true;
    }, 4000);
  }

}

servers.component.html:

<button class="btn btn-primary"
    [disabled]="AllowNewServerFunction()">Add Server</button>

Upvotes: 2

Views: 1006

Answers (3)

Avinash Dalvi
Avinash Dalvi

Reputation: 9301

Here is stackblitz : https://stackblitz.com/edit/disabled-button-duration

component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  allowNewServer = false;

  ngOnInit() {
    this.AllowNewServerFunction();
  }
  AllowNewServerFunction() {
    setTimeout(() => {
      this.allowNewServer = true;
   
    }, 4000);
  }
}

component.html

<button class="btn btn-primary"
    [disabled]="allowNewServer">Add Server</button>

Upvotes: 3

gkrthk
gkrthk

Reputation: 341

The method itself must return a Boolean. Right now it's just setting a property which is not used anywhere in html.

Try changing function to return Boolean instead of setting the variable

AllowNewServerFunction(
    { 
      setTimeout(()=>{
           return  true;
      },  4000);
      return false;
    }

Upvotes: 2

eko
eko

Reputation: 40647

The closest thing I can think of is to provide an observable with a delay if you really want to return a function type thing:

export class ServersComponent {
  isDisabled = of(true).pipe(delay(4000));
<button class="btn btn-primary"
    [disabled]="isDisabled | async">Add Server</button>

Stackblitz

Upvotes: 2

Related Questions