Angular:禁用带有指令的材质按钮不起作用 [英] Angular: disable material button with directive doesn't works

查看:31
本文介绍了Angular:禁用带有指令的材质按钮不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过指令禁用一些按钮(向按钮添加禁用属性).

此指令适用于经典的 html 按钮,但不适用于

参见stackblitz:https://stackblitz.com/edit/angular-5xq2wm

解决方案

如果将 mat-button 放置在 button 元素上,它将在内部投影到 mat-button 组件中.由于它是内容投影,因此您无法在构造函数中设置 disable true.

尝试 AfterViewInit

import { Component, Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';@指示({选择器:'[myDisableButton]'})导出类 HideCantEditDirective 实现 AfterViewInit {构造函数(私有 el:ElementRef,私有渲染器:Renderer2){//尝试使用 Renderer2this.renderer.setProperty(this.el.nativeElement, 'disabled', true);}ngAfterViewInit(){//尝试使用 ElementRefthis.el.nativeElement.disabled = true;this.renderer.setStyle(this.el.nativeElement, 'border', '2px 纯绿色');}}

分叉示例

I want through a directive disable some buttons (add disabled property to button).

This directive works on classic html button but doesn't works with angular material design button (mat-button):

import { Component, Directive, ElementRef, Renderer2 } from '@angular/core';


@Directive({
  selector: '[myDisableButton]'
})
export class HideCantEditDirective {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    // try with Renderer2
    this.renderer.setProperty(this.el.nativeElement, 'disabled', true);
    // try with ElementRef
    this.el.nativeElement.disabled = true;

    this.renderer.setStyle(this.el.nativeElement, 'border', '2px solid green');
  }
}



@Component({
  selector: 'my-app',
  template: `
  <button mat-button myDisableButton (click)="onClick()">Material Button</button><br /><br />
  <button myDisableButton (click)="onClick()">Classic Button</button>`,
  styles: [ 'button:disabled { border: 2px solid red !important; }' ]
})
export class AppComponent  {

  onClick(){
    alert('ok');
  }
}

Output:

See on stackblitz: https://stackblitz.com/edit/angular-5xq2wm

解决方案

If you place mat-button on button element it will be content projected into mat-button component internally. since it is content projected you are not able to set disable true in constructor.

Try AfterViewInit

import { Component, Directive, ElementRef, Renderer2, AfterViewInit } from '@angular/core';


@Directive({
  selector: '[myDisableButton]'
})
export class HideCantEditDirective implements AfterViewInit {
  constructor(private el: ElementRef, private renderer: Renderer2) {
    // try with Renderer2
    this.renderer.setProperty(this.el.nativeElement, 'disabled', true);

  }

  ngAfterViewInit(){
   // try with ElementRef
    this.el.nativeElement.disabled = true;

    this.renderer.setStyle(this.el.nativeElement, 'border', '2px solid green');
  }
}

Forked Example

这篇关于Angular:禁用带有指令的材质按钮不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆