1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > angular 7全局变量_如何使用CSS变量为Angular 7应用创建主题

angular 7全局变量_如何使用CSS变量为Angular 7应用创建主题

时间:2023-11-30 12:34:44

相关推荐

angular 7全局变量_如何使用CSS变量为Angular 7应用创建主题

angular 7全局变量

In this post, we will build a super simple cryptocurrency listing app using Angular 7 and CSS variables.

在本文中,我们将使用Angular 7和CSS变量构建一个超级简单的加密货币列表应用程序。

目录 (Table of Contents)

Design

设计

Project Setup

项目设置

Code

Conclusion, Repo, and Further Reading

结论,回购和进一步阅读

设计 (Design)

Feel free to skip this section if you’re only here for the code.

如果仅在此处查看代码,请随时跳过本节 。

I designed this simple app using Figma.

我使用Figma设计了这个简单的应用程序。

配色方案 (Color Scheme)

Our color scheme is made up offoreground,background,primary, anderrorcolors. Each color group has several lighter and darker variants of the base color.

我们的配色方案由前景色,背景色,原色和错误色组成。 每个颜色组都有几种较浅和较深的基色变体。

For our light/dark themes, the foreground and background colors will simply swap.

对于我们的浅色/深色主题,前景色和背景色将简单地互换。

组件 (Components)

Next up is to create the components. Since our app is pretty small, we only have a couple of components.

下一步是创建组件。 由于我们的应用程序很小,因此我们只有几个组件。

Thenavcomponent, which will let our user toggle the theme.

导航组件,它将使我们的用户可以切换主题。

Thetilecomponent which will display coin info.

将显示硬币信息的图块组件。

Putting it all together, we get our target designs.

综上所述,我们得到了目标设计。

项目设置 (Project Setup)

We are going to scaffold our app using the Angular CLI. First, we need to install it.

我们将使用Angular CLI搭建我们的应用程序。 首先,我们需要安装它。

npm install -g @angular/cli

Then create our app.

然后创建我们的应用程序。

ng new project-crypto

And finally, generate a module to hold our theming logic.

最后,生成一个模块来保存我们的主题逻辑。

cd project-crypto

ng generate module theme

码 (Code)

Alright, time for the good stuff.

好了,时间到了。

定义CSS变量 (Define CSS Variables)

Let’s start by defining out initial CSS variables. We can set them initially to reflect our light theme. Since we want our theme to be global, I have defined it using the:rootselector, which will match thehtmlelement. You could use thebodyor some other high-level element here if you wish.

让我们从定义初始CSS变量开始。 我们可以设置它们最初以反映我们的灯光主题。 因为我们希望我们的主题是全局的,所以我使用:root选择器定义了它,它将与html元素匹配。 如果愿意,可以在此处使用body或其他一些高级元素。

@import url("/css?family=PT+Sans:400,700");@import url("/css?family=Inconsolata:400,700");:root {/* Colors */--foreground-default: #08090a;--foreground-secondary: #41474d;--foreground-tertiary: #797c80;--foreground-quaternary: #f4faff;--foreground-light: #41474d;--background-default: #f4faff;--background-secondary: #a3b9cc;--background-tertiary: #5c7d99;--background-light: #ffffff;--primary-default: #5dfdcb;--primary-dark: #24b286;--primary-light: #b2ffe7;--error-default: #ef3e36;--error-dark: #800600;--error-light: #ffcecc;/* Shadows */--background-tertiary-shadow: 0 1px 3px 0 rgba(92, 125, 153, 0.5);}body {background: var(--background-default);}html,body {margin: 0;padding: 0;font-family: "PT Sans", sans-serif;}

定义主题 (Define the themes)

Next, let’s define our themes in TypeScript. These will later be used to toggle the theme by an Angular service.

接下来,让我们在TypeScript中定义主题。 稍后将使用它们通过Angular服务切换主题。

Under our newly createdthememodule, create a new file:theme.ts

在我们新创建的theme模块下,创建一个新文件:theme.ts

export interface Theme {name: string;properties: any;}export const light: Theme = {name: "light",properties: {"--foreground-default": "#08090A","--foreground-secondary": "#41474D","--foreground-tertiary": "#797C80","--foreground-quaternary": "#F4FAFF","--foreground-light": "#41474D","--background-default": "#F4FAFF","--background-secondary": "#A3B9CC","--background-tertiary": "#5C7D99","--background-light": "#FFFFFF","--primary-default": "#5DFDCB","--primary-dark": "#24B286","--primary-light": "#B2FFE7","--error-default": "#EF3E36","--error-dark": "#800600","--error-light": "#FFCECC","--background-tertiary-shadow": "0 1px 3px 0 rgba(92, 125, 153, 0.5)"}};export const dark: Theme = {name: "dark",properties: {"--foreground-default": "#5C7D99","--foreground-secondary": "#A3B9CC","--foreground-tertiary": "#F4FAFF","--foreground-quaternary": "#E5E5E5","--foreground-light": "#FFFFFF","--background-default": "#797C80","--background-secondary": "#41474D","--background-tertiary": "#08090A","--background-light": "#41474D","--primary-default": "#5DFDCB","--primary-dark": "#24B286","--primary-light": "#B2FFE7","--error-default": "#EF3E36","--error-dark": "#800600","--error-light": "#FFCECC","--background-tertiary-shadow": "0 1px 3px 0 rgba(8, 9, 10, 0.5)"}};

We can add as many themes as we like here. For now, let’s just stick with light and dark themes.

我们可以在此处添加任意多个主题。 现在,让我们仅坚持浅色和深色主题。

创建主题服务 (Create the theme service)

Our service will be responsible for:tracking the active theme, andupdating the CSS variablesbased on the active theme.

我们的服务将负责:跟踪活动主题,并根据活动主题更新CSS变量

We can use the CLI to generate our new service. Under/src/app/themerun

我们可以使用CLI生成新服务。 在/src/app/theme运行

ng generate service theme

import { Injectable } from "@angular/core";import { Theme, light, dark } from "./theme";@Injectable({providedIn: "root"})export class ThemeService {private active: Theme = light;private availableThemes: Theme[] = [light, dark];getAvailableThemes(): Theme[] {return this.availableThemes;}getActiveTheme(): Theme {return this.active;}isDarkTheme(): boolean {return this.active.name === dark.name;}setDarkTheme(): void {this.setActiveTheme(dark);}setLightTheme(): void {this.setActiveTheme(light);}setActiveTheme(theme: Theme): void {this.active = theme;Object.keys(this.active.properties).forEach(property => {document.documentElement.style.setProperty(property,this.active.properties[property]);});}}

Some things to note here:

这里要注意一些事情:

We import our theme definitions that we just created, on line 2.我们在第2行中导入刚创建的主题定义。 Lines 34–39 update our CSS variables defined in the theme. This is essentially where the magic is happening.第34–39行更新了主题中定义CSS变量。 这基本上就是魔术发生的地方。

Since, in this example app, we only have two themes, I have added some convenience functions to set the theme to light and dark directly. You can use thegetAvailableThemesandsetActiveThemefunctions to change the theme dynamically based on user input instead.

由于在此示例应用程序中,我们只有两个主题,因此我添加了一些便捷功能以将主题直接设置为亮和暗。 您可以使用getAvailableThemessetActiveTheme函数来根据用户输入动态更改主题。

组件 (Components)

The hard work is done. Now we just need to put our building blocks together. Well, actually, first we need to create the building blocks ?. Let’s create the components.

辛苦了。 现在,我们只需要将我们的构建块放在一起。 好吧,实际上,首先我们需要创建构建基块?。 让我们创建组件。

We will start with thenavcomponent. Again, we can use the Angular CLI to give us a head start.

我们将从nav组件开始。 同样,我们可以使用Angular CLI抢先一步。

ng generate component nav

import { Component, OnInit } from "@angular/core";import {faLightbulb as faSolidLightbulb,faDollarSign,IconDefinition} from "@fortawesome/free-solid-svg-icons";import { faLightbulb as faRegularLightbulb } from "@fortawesome/free-regular-svg-icons";import { ThemeService } from "src/app/theme/theme.service";@Component({selector: "app-nav",templateUrl: "./ponent.html",styleUrls: ["./ponent.css"]})export class NavComponent implements OnInit {faLightbulb: IconDefinition;faDollarSign = faDollarSign;constructor(private themeService: ThemeService) {}ngOnInit() {this.setLightbulb();}setLightbulb() {if (this.themeService.isDarkTheme()) {this.faLightbulb = faRegularLightbulb;} else {this.faLightbulb = faSolidLightbulb;}}toggleTheme() {if (this.themeService.isDarkTheme()) {this.themeService.setLightTheme();} else {this.themeService.setDarkTheme();}this.setLightbulb();}}

Note:I have used Font Awesome for the icons on the nav bar. If you want to do the same, you will need to install Font Awesome for Angular.

注意:我已经在导航栏上的图标中使用了Font Awesome。 如果要执行相同的操作,则需要为Angular安装Font Awesome 。

The logic for our nav component is pretty straight forward. We set our icon depending on the theme on initialization (line 22). Then we set up an event handler to toggle the theme. You can see it’s usage in the HTML below.

导航组件的逻辑非常简单。 我们根据初始化时的主题设置图标(第22行)。 然后,我们设置一个事件处理程序来切换主题。 您可以在下面HTML中查看其用法。

<nav><fa-icon [icon]="faDollarSign"></fa-icon><h5 class="title secondary-font">ProjectCrypto</h5><fa-icon [icon]="faLightbulb" (click)="toggleTheme()"></fa-icon></nav>

nav {height: 4rem;display: flex;align-items: center;padding-left: 1rem;padding-right: 1rem;background-color: var(--background-tertiary);color: var(--foreground-quaternary);font-size: 1rem;}nav .title {margin-left: auto;margin-right: auto;}

Notes on the nav component CSS:

关于导航组件CSS的注释:

Line 7, and 8 are the important ones here. These are the two lines that use our previously defined CSS variables, and make this component themeable.7号线和8号线在这里很重要。 这两条线使用了我们先前定义CSS变量,并使该组件成为主题。

Next, thetilecomponent.

接下来,平铺组件。

<div class="container"><h5 class="name">{{ name }}</h5><h5 class="price"><fa-icon [icon]="currencyIcon"></fa-icon>{{ price | number }}</h5><fa-icon[icon]="faHeart"(click)="onToggleFavourite()"class="favouriteIcon icon"[ngClass]="{ isFavourite: isFavourite }"></fa-icon></div>

.container {display: grid;grid-template-columns: 0.5fr 1fr 0.5fr;align-items: center;border-radius: 0.5rem;background: var(--background-light);color: var(--foreground-tertiary);padding-left: 0.5rem;padding-right: 0.5rem;margin-bottom: 1rem;min-height: 8rem;box-shadow: var(--background-tertiary-shadow);}.container .name {justify-self: start;}.container .price {justify-self: center;}.container .icon {justify-self: end;}.favouriteIcon {font-size: 1.5rem;}.isFavourite {color: var(--primary-default);}

Notes:

笔记:

The TypeScript for our tile component doesn’t have any theming logic, so I have omitted it here.图块组件的TypeScript没有任何主题逻辑,因此在此省略了。 Lines 6, 7, 12, and 32 are what enable our tile component to be themeable.第6、7、12和32行使我们的tile组件具有主题性。

结论,回购和进一步阅读 (Conclusion, Repo, and Further Reading)

And that’s it! You now have the components and theme created. You can add the components to your base app component to wire everything up with some test data.

就是这样! 现在,您已经创建了组件和主题。 您可以将组件添加到基本应用程序组件中,以将所有内容与一些测试数据连接起来。

You can find the repo here.

您可以在此处找到该回购。

Learn more about CSS Variables here.

在此处了解有关CSS变量的更多信息。

Thanks for reading!

谢谢阅读!

翻译自: /news/how-to-create-themes-for-your-angular-7-apps-using-css-variables-69251690e9c5/

angular 7全局变量

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。