Reputation: 466
I have a <app-my-table></app-my-table>
component that accepts showActions
as input.
I usually use it like this <app-my-table [showActions]="true"></app-my-table>
I would appreciate if I can make it work using this syntax too:
<app-my-table showActions></app-my-table>
Please see example below:
https://stackblitz.com/edit/angular-component-property
Upvotes: 1
Views: 42
Reputation: 718
If you want to do that you can create a new directive and then inject this directive in the constructor of your Component.
constructor(@Self() @Optional() private showActionsDir: ShowActionsDirective) {
if (showActionsDir) {
this.showActions = true;
}
}
Mind the @Optional
and @Self
decorators so that angular won't throw an error when the directive isn't found and that it only searches in the local injector of the component.
@trichetriche's answer works as well but it isn't really expressive in my opinion. On the other hand, the way I provided can be looked at as too much unnecessary code and a useless directive because it only is a marker for the component and has no other functionality.
If I were you I would choose the most explicit way available, which you've already shown in the question ([showActions]="true"
).
Upvotes: 2
Reputation:
private _showActions = null;
public set showActions(value: any) {
this._showActions = value === '';
...
To explain a bit :
When you use the @Input
decorator, you can define a default value to your variables. Here, we will use null
as the default, although you could just use undefined
.
When you write your input in your component selector like you want to (<x showActions>
), you actually write a shorthand. The real syntax is
<x showActions="">
This means that your input value, when you don't provide one, is the empty string ''
.
This means that all you have to is compare the input value to an empty string, and set your internal variables accordingly.
Upvotes: 0