Issue
I built a PageHeaderComponent
which will be built based on the buttons
array.
While I was able to bind the (click)
event correctly to the method in the parents component I am struggling to bind the condition for the [disabled]
status of the button-secondary
correctly.
In my case the disabled status will be set correctly initially. But in case the condition changes at runtime the disabled
status won't be updated. What would be the correct way to bind the disabled condition?
parent.component.ts
@Component({
templateUrl: 'parent.component.html',
styleUrls: ['parent.component.sass'],
encapsulation: ViewEncapsulation.None
})
export class ParentComponent implements OnInit {
...
selectedTasks: TaskViewModel[] = [];
buttons: Button[] = [
{
click: () => this.openModal(),
disabled: !this.selectedTasks || this.selectedTasks.length == 0,
icon : 'plus-circle-solid',
text: this.translateService.instant('component.tasks.new-task')
},
{
click: () => this.openDeleteTaskModal(),
disabled: !this.selectedTasks || this.selectedTasks.length == 0,
icon : 'times-circle',
text: this.translateService.instant('component.tasks.new-task')
},
]
openModal() {
}
...
}
parent.component.html
<div page-header
title="{{'component.tasks.title' | translate}}"
[buttons]="buttons">
</div>
...
page-header.component.html
<div class="row page-header">
<ng-container *ngFor="let button of buttons" >
<button-secondary
text="{{ button.text | translate}}"
(click)="button.click($event)"
icon = "icon icon-{{button.icon}}"
[id]="button.id"
[disabled] = "button.disabled"
>
</button-secondary>
</ng-container>
</div>
Solution
You can create getters for that, but you have to add an unwanted variable to your buttons because of the scope of getters.
buttons: Button[] = [
{
_parent: this,
click: () => this.openModal(),
get disabled() { return !this._parent.selectedTasks || this._parent.selectedTasks.length == 0 },
icon: 'plus-circle-solid',
text: this.translateService.instant('component.tasks.new-task'),
},
{
_parent: this,
click: () => this.openDeleteTaskModal(),
get disabled() { return !this._parent.selectedTasks || this._parent.selectedTasks.length == 0 },
icon: 'times-circle',
text: this.translateService.instant('component.tasks.new-task'),
},
];
Answered By - MGX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.