I am trying to understand if this is possible or not in Angular. Instead of defining a control binding in template:
<button [disabled]="helper.disabled"></button>
Can I send the control, without any binding defined in the template, to a helper class and set the binding there?
The code example below does not work. It does not set up a working databinding that later can be used in randomMethod() to change the disabled state of the button.
Have I just set the binding in wrong lifecycle or misunderstood something else?
// ***** my-component.html ****************
...
<button #myButton></button>
...
// ***** my-component.ts ****************
...
@ViewChild('myButton') myButton: Button;
protected helper: Helper;
ngOnInit(): void {
this.helper = new Helper();
}
ngAfterViewInit(): void {
this.helper.initButton(this.myButton);
this.cdref.detectChanges();
}
...
// ***** helper.ts ****************
public disabled boolean;
public initButton(button:Button): void{
button.disabled = this.disabled; // <-- HOW TO?
}
private randomMethod(){
this.disabled = true;
}
CodePudding user response:
@ViewChild gives an ElementRef, using the native element property of the ElementRef you can set the disabled property
// Component
@ViewChild('myButton') myButton: ElementRef;
// Helper
public initButton(button: ElementRef): void {
button.nativeElement.disabled = this.disabled;
}