如何防止在角度中通过父组件单击禁用按钮?

时间:2018-06-14 14:49:57

标签: angular button components disabled-input

我有一个包含按钮元素的通用组件app-button

按钮组件html

<button [type]="type" [disabled]="isLoading || !!disabled">
    <ng-content></ng-content>
</button>

按钮组件ts

@Component({
  selector: 'app-button',
  templateUrl: 'views/button.component.html',
  styleUrls: ['styles/button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() type: string;
  @Input() color: string;
  @Input() disabled: boolean;
  @Input() class: string;
  isLoading: boolean;
  constructor() {
    this.type = "submit";
  }
}

我添加(点击)我的组件,它工作正常。但是,当我添加disabled属性时,它会禁用按钮,但单击内容时(点击)仍然有效。

<app-button (click)="signIn()" [disabled]="true">
    <span>Signin</span>
</app-button>

1 个答案:

答案 0 :(得分:1)

我认为你的问题就是你 禁用组件,您在父组件中有单击事件

解决方案可能是将您的(click)="signIn()"移动到您的子组件,它将被禁用并添加@Output装饰器以接收来自孩子的callback

子组件html

<button [type]="type" [disabled]="isLoading || !!disabled" (click)="signIn()">
    <ng-content></ng-content>
</button>

子组件ts

@Component({
  selector: 'app-button',
  templateUrl: 'views/button.component.html',
  styleUrls: ['styles/button.component.scss']
})
export class ButtonComponent implements OnInit {
  @Input() type: string;
  @Input() color: string;
  @Input() disabled: boolean;
  @Input() class: string;
  @Output() callback = new EventEmitter();
  isLoading: boolean;
  constructor() {
    this.type = "submit";
  }

  signIn(){
     this.callback.emit();
  }

}

父组件html

<app-button (callback)="signIn()" [disabled]="true">
    <span>Signin</span>
</app-button>

Demo StackBlitz