According to the nativescript's UI & Styling docs, nativescript currently supports only the :highlighed
pseudo selector on Button.
You should use it like this:
.my_button_2:highlighted {
background:olive;
border-color: red;
border: 2;
border-width: 2;
}
Note: by default on Android, the Button element is not focusable. So if you want to enable focus on an Android Button element, you need to first add modifications to its native component (android.widget.Button) using the following:
Add a 'loaded' eventlistener:
<Button (loaded)="onButtonLoaded($event)" text="My Button 2" class="my_button_2"></Button>
Then, when the element is loaded, enable focus:
import { Button } from "@nativescript/core";
export class AppComponent {
onButtonLoaded(event: TapGestureEventData) {
const btn = event.object as Button;
const androidButton = btn.android;
androidButton.setFocusableInTouchMode(true); // make Button focusable
}
}
This makes the Button focusable, and you can focus on it manually like so:
import { Component, ElementRef, ViewChild } from "@angular/core";
import { Button } from "@nativescript/core";
export class AppComponent {
@ViewChild("btn") btn: ElementRef<Button>;
focusBtn() {
const isFocused = this.btn.nativeElement.focus();
console.log(`did focus? ${isFocused}`);
}
}
Note: You still can't use the button:focus
css pseudo-selector due to the framework limitation to :highlighted
as described above.
However, to solve your case, as a work around if your scenario is to set the focus manually, then you can use the following to achieve a focus-similar behavior (works on both Android and iOS):
CSS:
.focus {
background:yellow;
border-color: red;
border: 2;
border-width: 2;
}
.html template:
<Button (loaded)="onButtonLoaded($event)" text="My Button 2" class="my_button_2" [ngClass]="{ 'focus': buttonIsFocused }"></Button>
.ts:
export class AppComponent {
buttonIsFocused = false;
focusOnButton() {
// call this when you wish to add focus styling to the button
this.buttonIsFocused = true;
}
defocusButton() {
// call this when you wish to remove the focus styling
this.buttonIsFocused = false;
}
}
Check this to read more about nativescript styling.
Check this and this to read more about the native iOS focusing.