How to set disabled button property using a function?

Viewed 154

I'm trying:

  • To have a button disabled by default.
  • After 4 seconds, the button will be enabled by using a function.

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>
3 Answers

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>

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;
    }

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

Related