Angular ngstyle не работает

Директивы

Директивы определяют набор инструкций, которые применяются при рендеринге html-кода. Директива представляет класс с директивными метаданными. В TypeScript для прикрепления метаданных к классу применяется декоратор @Directive .

В Angular есть три типа директив:

Компоненты : компонент по сути также является директивой, а декоратор @Component расширяет возможности декоратора @Directive с помощью добавления функционала по работе с шаблонами.

Атрибутивные : они изменяют поведение уже существующего элемента, к которому они применяются. Например, ngModel , ngStyle , ngClass

Структурные : они изменяют структуру DOM с помощью добавления, изменения или удаления элементов html. Например, это директивы ngFor и ngIf

ngClass и ngStyle

ngClass

Директива ngClass позволяет определить набор классов, которые будут применяться к элементу. В качестве значения она принимает набор классов в следующем виде:

Читайте также:  Total commander настроить горячие клавиши

Например, определим следующий компонент:

В секции styles у компонента определены два класса, которые устанавливают различные стилевые свойства шрифта: verdanaFont и segoePrintFont.

В шаблоне для привязки класса к элементу применяется директива [ngClass]=»» . Эта директива принимает js-объект, в котором ключи — это названия классов. Этим названиям присваиваются булевые значения true (если класс применяется) и false (если класс не применяется). То есть в данном случае класс verdanaFont будет применяться ко всему блоку div.

Однако в блоке div есть параграф, и мы, допустим, хотим, чтобы к этому параграфу применялся другой класс. А по умолчанию вложенный параграф унаследует стили от родительского блока div и также применяет класс segoePrintFont, в котором можно переопределить унаследованные стили.

Вместо жестко закодированных значений true/false мы можем использовать привязку к выражениям:

В качестве альтернативы мы можем использовать следующие выражения привязки:

Выражение [class.verdanaFont]=»true» указывает, что класс verdanaFont будет применяться для данного элемента.

Однако с помощью ngClass мы можем задать целый набор классов, которые применяются к элементу:

В данном случае для элемента устанавливаются два класса verdanaFont и navyColor.

ngStyle

Директива ngStyle позволяет задать набор стилей, которые применяются к элементу. В качестве значения директива принимает js-объект, в котором ключи — названия свойств CSS:

Аналогично для установки стилей можно применять свойства объекта style:

Также мы можем установить привязку

Динамическое изменение стилей

Директивы ngClass и ngStyle позволяют устанавливать привязку к выражениям, благодаря чему мы можем динамически менять стили или классы. Например:

Выражение [ngClass]=»» устанавливает для класса invisible привязку к значению переменной visibility . По нажатию на кнопку мы можем переключать это свойство, тем самым управляя видимостью блока.

В качестве альтернативы также можно было бы использовать следующее выражение:

Источник

angularjs ng-style: фоновое изображение не работает

Я пытаюсь применить фоновое изображение к div, используя angular ng-style (Я пробовал пользовательскую директиву раньше с тем же поведением ), но она, похоже, не работает.

хотя, если я попробую цвет фона, он, кажется, работает нормально. Я попробовал удаленный источник и локальный источник тоже http://lorempixel.com/g/400/200/sports/ , ни один не работал.

7 ответов

синтаксис background-image — это:

правильный синтаксис для ng-стиля:

можно анализировать динамические значения несколькими способами.

интерполяция с двойными фигурными скобками:

конкатенации строк:

ES6 шаблон литералов:

Если у вас есть данные, вы ждете возвращения сервера (item.id) и иметь такую конструкцию:

убедитесь, что вы добавили что-то вроде ng-if=»item.id»

в противном случае у вас будет либо два запроса, либо один неисправный.

для тех, кто изо всех сил пытается получить эту работу с IE11

HTML-код

JS

это работает для меня, фигурные скобки не требуются.

уведомления.значок здесь-переменная области.

Если у нас есть динамическое значение, которое должно идти в фоновом режиме css или атрибут background-image, это может быть немного сложнее указывать.

предположим, у нас есть функция getImage() в нашем контроллере. Этот функция возвращает строку, отформатированную аналогично этой: url (иконки / ручка.формат PNG.) Если мы это сделаем, в объявлении ngStyle указывается точно так же, как и раньше:

Не забудьте поставить кавычки вокруг background-имя ключа изображения. Помните, что это должно быть отформатировано как допустимый ключ объекта Javascript.

только для записей вы также можете определить свой объект в контроллере следующим образом:

и затем вы можете определить функцию для изменения свойства объекта напрямую:

делая это таким образом, вы можете изменить dinamicaly свой стиль.

Источник

ngClass и ngStyle¶

ngClass¶

Директива ngClass позволяет определить набор классов, которые будут применяться к элементу. Например, определим следующий компонент:

В секции styles у компонента определены два класса, которые устанавливают различные стилевые свойства шрифта: verdanaFont и segoePrintFont .

В шаблоне для привязки класса к элементу применяется директива [ngClass]=»» . Эта директива принимает js-объект, в котором ключи — это названия классов. Этим названиям присваиваются булевые значения true (если класс применяется) и false (если класс не применяется). То есть в данном случае класс verdanaFont будет применяться ко всему блоку div .

Однако в блоке div есть параграф, и мы, допустим, хотим, чтобы к этому параграфу применялся другой класс. А по умолчанию вложенный параграф унаследует стили от родительского блока div и также применяет класс segoePrintFont , в котором можно переопределить унаследованные стили.

В качестве альтернативы мы можем использовать следующие выражения привязки:

Выражение [class.verdanaFont]=»true» указывает, что класс verdanaFont будет применяться для данного элемента.

ngStyle¶

Директива ngStyle позволяет задать набор стилей, которые применяются к элементу. В качестве значения директива принимает js-объект, в котором ключи — названия свойств CSS:

Аналогично для установки стилей можно применять свойства объекта style :

Динамическое изменение стилей¶

Директивы ngClass и ngStyle позволяют устанавливать привязку к выражениям, благодаря чему мы можем динамически менять стили или классы. Например:

Выражение [ngClass]=»» устанавливает для класса invisible привязку к значению переменной visibility . По нажатию на кнопку мы можем переключать это свойство, тем самым управляя видимостью блока.

В качестве альтернативы также можно было бы использовать следующее выражение:

Источник

AngularJS ng-style with a conditional expression

I am handling my issue like this:

But to avoid having this function on the controller side, I would much prefer to do something like this:

How can I do this?

11 Answers 11

OR the same result:

other conditional possibility:

As @Yoshi said, from angular 1.1.5 you can use-it without any change.

If you use angular

You can achieve it like that:

@jfredsilva obviously has the simplest answer for the question:

However, you might really want to consider my answer for something more complex.

Something more complex:

If $scope.color == ‘blueish’ , the color will be ‘blue’.

If $scope.zoom == 2 , the font-size will be 26px.

if you want use with expression, the rigth way is :

but the best way is using ng-class

On a generic note, you can use a combination of ng-if and ng-style incorporate conditional changes with change in background image.

For single css property

For multiple css properties below can be referred

Replace 1==1 with your condition expression

I am doing like below for multiple and independent conditions and it works like charm:

also this syntax for ternary operator will work:

where are $scope property values. In example:

this allows for some calculaton into the css property values.

I am using ng-class for adding style :-

Using ternary operator along with ng-class directives in angular.js for giving style. Then define the style for class in .css or .scss file. Eg :-

Ok i was previously not aware that AngularJS usually refers to Angular v1 version and only Angular to Angular v2+

This answer only applies for Angular

Leaving this here for future reference..

Not sure how it works for you guys but on Angular 9 i have to wrap ngStyle in brackets like this:

Источник

Using ngStyle in Angular for dynamic styling

Learn Angular the right way!

Everything you need to become an Angular expert

Google Developer Expert

59 lessons

116 lessons

44 lessons

39 lessons

47 lessons

35 lessons

NGRX Store + Effects

41 lessons

See Courses

Styling is a lot of fun. We mostly define CSS classes to make styles reusable and consistent. However, we need to style an element inline sometimes. Additionally, we need to dynamically change inline styles based on the application state.

In this article, we will look at how to style elements inline using the style attribute. Even more excitingly, we will explore how to dynamically change inline styles in Angular using two very stylish tools: binding to the style property, and ngStyle directive. Cool bananas!

You can also check out our other post on using ngClass!

Table of contents

Inline styling using the style attribute

The style attribute is a global attribute that is available to all HTML elements. It lets us provide style information for individual elements, in other words, it lets us style an element inline.

The string assigned to the style attribute contains a CSS style declaration block. A declaration block can have one or more declarations. Each declaration is a CSS property and value pair .

CSS style declaration:

However, when styling inline we do not need to put curly braces to create a block. Also, we would replace ‘css-property’ above with actual CSS property names.

There are many, many CSS properties that we can use. Some common CSS properties are padding , margin and font .

Most importantly, inline styles override the styles in the component and global stylesheets.

Let us have a quick look at stylesheets in Angular.

Stylesheets in Angular

Angular has a modular design for defining styles. Each component has its own stylesheet which styles only that component. Additionally, there is a global stylesheet for styles that apply to the whole application.

Let’s see an example:

The inline style for the p element replaces the background-color and color styles from the element selector. Only the CSS properties that are overridden are replaced, therefore, the p still inherits the style for padding (and any cascading styles from the global stylesheets).

Attributes vs Properties

Before we look at how to dynamically style elements, it is important to highlight the connection between attributes and properties.

Without getting into too much detail, the gist is, attributes are used in the HTML document, at development time, to configure the HTML elements. However, the attributes only provide the initial values, for example, the initial background colour in our style attribute.

🎉 Download it free!

Ready to go beyond ForEach? Get confident with advanced methods — Reduce, Find, Filter, Every, Some and Map.

  • Fully understand how to manage JavaScript Data Structures with immutable operations
  • 31 pages of deep-dive syntax, real-world examples, tips and tricks
  • Write cleaner and better-structured programming logic within 3 hours

✅ Success! Check your email, enjoy.

As an extra bonus, we’ll also send you some extra goodies across a few extra emails.

We often need to change these values while the application is running based on some interaction or some logic. For example, highlight products on sale by changing the background colour of the elements that display those products.

Dynamic changes are made with JS/TS code where the HTML elements are represented as objects and the attributes are represented as the properties of these objects. Therefore, to dynamically change the values we need to change the properties. For example, to change the style, we need to change the style property values.

If we inspect the p tag in our example code above, we would see that it has a property called style. The style property is an object as well and has all the CSS properties as its properties. Remember, CSS properties are things like, display , background-color , top and are dash-case. They are camelCased as properties on the style object.

Now, let us look at how to dynamically change inline styles in Angular.

Property binding with “style”

Property binding is the right fit when styling only one CSS property.

Firstly, the square brackets denote a property binding and contain the property that we want to set and update dynamically.

However, binding to the style property looks slightly different from other property bindings. This is because the style property is an object itself, with the CSS properties as its properties. Therefore, we also need to specify the actual CSS property to style.

You may find it surprising that we can use the dash-case for the CSS property since the JavaScript representation is camelCased. Angular lets us use either, but it is better to use the dash-case since it is consistent with the style attribute, as well as, it is what we’re used to in CSS declarations and also because Angular provides it to us.

The second part of the property binding is the template expression. The string assigned to the binding is a template expression which gets evaluated to a value.

In our case, it should evaluate to the CSS property value that we want to assign to the CSS property. For example, for background-color, the template expression could evaluate to the value #dda0dd.

Whenever the template expression evaluates to a different value from before, the change detection system will apply the new style to the view.

Example

It is time to see an example. Since we’re talking about styles, it is “fitting” to imagine a simple application that lets users browse for hair and if they like it they can get it. We want to help the user out by pointing out the hair that is trending and ones that are a good bargain.

OK, yes, this is based on Ariana Grande’s song:

“You like my hair? Gee, thanks, just bought it. I see it, I like it, I want it, I got it (Yeah)”!

It is a catchy song.

Template expression context

The context for template expressions is the component instance. Meaning, the template expression can access the properties and methods of the component class.

To illustrate this, let us implement the logic for figuring out the background colour in a method. We will highlight the hair items in three categories: trending, trending and a bargain price (shoppers would definitely do not want to miss these), and not trending but are a bargain (maybe it is still worth getting it).

We can call the method in the template expression:

Now, let us see how Angular makes it easy for us to bind to CSS properties that need a unit extension.

Optional unit property

Some CSS style properties like font-size, margin, padding, width, height, and plenty others need a unit of measurement. The values for these properties are not complete without a unit or the style will not take effect.

Angular gives us a more stylish way to provide the unit. We can specify the unit in the property binding using the dot notation:

Other units include vh and vw .

When we don’t want to use property binding for inline styling

There isn’t much value in using property binding to bind to a static string.

Use the style attribute if the value is not expected to change. Even better, we can put the styles in the stylesheet instead of inline.

Styling multiple CSS style properties inline

Property binding lets us bind to one property at a time making it suitable for styling a single property on an element.

If we want to style multiple CSS properties:

It is time to use the NgStyle directive!

Angular’s NgStyle Directive

Use NgStyle directive to dynamically style multiple CSS properties of an element.

ngStyle is applied as an attribute to an element. The square brackets around the directive indicate that the NgStyle directive has an input property also called ngStyle. It is a common pattern to define the directive and bind to its input property at the same time. This is how we can pass our style information to the ngStyle directive.

To find out what value the input property expects, let us look at how Angular implements it:

As we see ngStyle expects an object with key and value pairs. The keys are CSS property names and the values are expressions that evaluate to CSS property values.

Here are some of the ways we can pass in the styles as input:

  1. Define a property in our component class for the styles
  1. Call a method in our component class that returns an object with the styles

As a side note, and just for completion, we could optionally use camelCase for the keys, in which case we do not need to put them in strings:

However, to use the optional unit property, we have to provide the keys in strings:

It is important to be consistent.

So, there we have it. Use property binding to style one CSS property of an element and use the ngStyle directive to set multiple CSS properties. Both tools make it super easy to dynamically style elements.

To learn more techniques, best practices and real-world expert knowledge I’d highly recommend checking out my Angular courses — they will guide you through your journey to mastering Angular to the fullest!

Learn Angular the right way!

Everything you need to become an Angular expert

Google Developer Expert

59 lessons

116 lessons

44 lessons

39 lessons

47 lessons

35 lessons

NGRX Store + Effects

41 lessons

See Courses

Detecting @​Input changes in Angular with ngOnChanges and Setters

In this post you’ll learn how to detect changes to an @Input property in Angular. We’ll explore both using ngOnChanges lifecycle hook and also more.

Getting Query Params from Angular’s Router

In this post you’re going to learn how get query params from the URL in Angular by using the router snapshot, and also how to subscribe to route pa.

Handling Observables with NgFor and the Async Pipe

Now you’ve learned the basics of Angular’s NgFor it’s time to take things up a notch and introduce some Observables. In this article you’ll learn h.

Angular Classes with NgClass

In this post you’ll learn how to use the NgClass directive in Angular to dynamically assign class names to elements or components.

Accessing the index inside NgFor

In this post you’re going to learn how to access the index of the current array element using Angular’s NgFor directive!

Getting Element references (ElementRef) in Angular templates

In this post you’re going to learn how to reference an element inside an Angular template.

Join our email community

Developer tips and tricks, motivation, discounts and new course launches.

No spam, just awesome stuff. Read the legal things if you fancy it.

Ready to go beyond ForEach? Get confident with advanced methods — Reduce, Find, Filter, Every, Some and Map.

✅ Success! Check your email, enjoy.

Build your first NestJS app. With the CLI you’ll learn the basics of real-world NestJS development.

✅ Success! Check your email, enjoy.

Ultimate Courses™ © 2016-2021.

Ultimate Angular Limited trading as Ultimate Courses.

Company No. 07690582. VAT No. GB263855379. Made in the UK

We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.

A newer version of this site just became available. Please refresh this page to activate it.

Источник

Оцените статью