简体   繁体   中英

How to apply ngStyle style on focus state in Angular 9

I have a style that I only want to apply to an element when it's state is 'focus'. Most of the colours for this site come from an API so I'm injecting them in where needed with ngStyle which has worked great up until I only needed one applied when focused into a text box.

<div class="form__group__full">
    <input type="text" class="form__field" id="callbackName" [(ngModel)]="name" placeholder="e.g. John" 
    [ngStyle]="{'color': brand?.colours.primary, 
                  'border-bottom': '2px solid ' + brand?.colours.secondary, 
                  'border-image:focus': 'linear-gradient(to right, ' + brand?.colours.primary + ', ' + brand?.colours.secondary + ')'}">
    <label for="callbackName" class="form__label">Name</label>
</div>

The border-bottom and color properties work fine, but the border-image property was just a stab in the dark to be honest - how can I apply a style dynamically only when the object is in the focus state and without calling a pre-defined class in a stylesheet?

You could introduce a boolean flag (eg. focus ) in the controller and use it to set the styles. Adjust the focus flag based on focus and blur events.

Try the following

Controller

export class SampleComponent {
  focus = false;    // <-- default value
  ...
}

Template

<div class="form__group__full">
  <input (focus)="focus=true" (blur)="focus=false" type="text" class="form__field" id="callbackName" [(ngModel)]="name" placeholder="e.g. John" 
    [ngStyle]="focus ? {'color': brand?.colours.primary, 
                'border-bottom': '2px solid ' + brand?.colours.secondary, 
                'border-image:focus': 'linear-gradient(to right, ' + brand?.colours.primary + ', ' + brand?.colours.secondary + ')'} : ''"
  >
  <label for="callbackName" class="form__label">Name</label>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM