发送消息时禁用Button并对其应用CSS类

时间:2019-05-06 18:38:00

标签: angular typescript

在具有形式的7角组件上,我具有以下内容:

export class MessageComponent implements OnInit { 

  message: FormGroup;

  constructor(private formBuilder: FormBuilder, private messageService: MessageService) { }

  ngOnInit() {

    this.message = this.formBuilder.group({ 
      content: ['']
    });

  }

  onSubmit() {

    if (this.message.valid) {

      let request: SendMessageRequest = { 
        content: this.message.value.content
      };

      this.messageService.send(request).subscribe(
        (response: SendMessageResponse) => { 
          this.message.reset();
        },
        (error) => {
          // Do something with errors           
        }
      );

    }
  }
}

HTML格式如下:

  <form [formGroup]="message" (ngSubmit)="onSubmit()">
    <label for="content">Content</label>
    <textarea id="message" formControlName="content"></textarea>
    <button class="action" type="submit">Send Message</button>
  </form>

在服务正在发送消息时如何禁用按钮?

以及如何将特定的CSS类应用于禁用的按钮?

2 个答案:

答案 0 :(得分:2)

您可以有条件地添加一个类(使用ngClass)到按钮并显示微调器或将其禁用。除了将css类设置为禁用之外,还可以将button属性设置为disabled,它应该显示为禁用。

例如:

<button class="action" type="submit" [ngClass]="{'disabled': sendDisabled}" [disabled]="sendDisabled">Send Message</button>

在组件中:

onSubmit() {

        if (this.message.valid) {

            let request: SendMessageRequest = {
                content: this.message.value.content
            };
            this.sendDisabled=  true;
            this.messageService.send(request).subscribe(
                (response: SendMessageResponse) => {
                    this.message.reset();

                  this.sendDisabled = false; // received response enable button
                },
                (error) => {
                    // Do something with errors           
                }
            );

        }
    }

确保在组件中定义了sendDisabled。 在CSS中,为禁用的类添加样式:

button.disabled{
  pointer-events: none;
}

答案 1 :(得分:0)

您可以使用ng-class设置条件:

<button [class.action]="myCondItion" type="submit">Send Message</button>

TS

myCondItion: boolean = false;
disableButton: boolean= false;
 constructor(private formBuilder: FormBuilder, private messageService: MessageService) { }

ngOnInit() {
  this.message = this.formBuilder.group({ 
    content: ['']
  });
}

onSubmit() {
 if (this.message.valid) {

  let request: SendMessageRequest = { 
    content: this.message.value.content
  };
  this.myCondItion= true; //showClass
  this.messageService.send(request).subscribe(
  this.disableButton = true;
    (response: SendMessageResponse) => { 
      this.message.reset();
    },
    (error) => {
      // Do something with errors           
    }
   );
  }
 }
}