2

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>
1
  • What do you think AllowNewServerFunction method is returning? Commented May 24, 2021 at 14:15

3 Answers 3

3

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>

Sign up to request clarification or add additional context in comments.

3 Comments

You don't need to return true; in the AllowNewServerFunction method since it's not doing anything :-) I thought about this too but OP says: "Maximilian instructor used a constructor. But I want to use a function instead". So I thought using constructor or life-cycles were out of bounds
my bad forgot to save changes. Thanks
Hi sorry for delay, i'll test it soon with my own project & will make sure to reply back.
2

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

2 Comments

This is better way can achieve this 👍🏻
Hi sorry for delay, i'll test it soon with my own project & will make sure to reply back.
2

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

1 Comment

Hi sorry for delay, i'll test it soon with my own project & will make sure to reply back.

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.