简体   繁体   English

输入路由器出口后更改CSS

[英]Css changed after inputting router-outlet

I was developing a login screen within angular with the within the app.component.html as such: 我正在用app.component.html角开发一个登录屏幕,如下所示:

app.component.ts app.component.ts

<div class="container">
   <app-login></app-login>
</div>

and css as such: 和CSS这样:

login.css login.css

.form-group {
  display: block;
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin: 0 0 5px 0;
}

app.component.css app.component.css

.container {
  display: grid;
  height: 100%;
}

app-login {
  width: 100%;
  max-width: 274px;
  place-self: center;
}

However, since I have now incorporated routing into my app, I display the login page using the <router-outlet> component, but this has ruined the CSS of the login page is it once was... 但是,由于我现在已将路由合并到我的应用程序中,因此我使用<router-outlet>组件显示登录页面,但是这曾经毁了登录页面的CSS。

app.component.ts app.component.ts

<div class="container">
   <router-outlet></router-outlet>
</div>

在此处输入图片说明

How can I change my CSS files such that I can get back the look I once had? 如何更改CSS文件,以便恢复以前的外观?

Here is a stackblitz to my example 这是我的例子的闪电战

Update Solution found to the missing CSS (see below) 找到丢失的CSS的更新解决方案(请参见下文)

However now it appears is hogging much of the screen, pushing my element downward? 但是现在看来,它占据了屏幕的大部分,从而将我的元素向下推?

You need to set 你需要设置

encapsulation: ViewEncapsulation.None

on the AppComponent to allow styles to affect also those components which are used inside AppComponent . AppComponent上允许样式也影响在AppComponent内部使用的那些组件。

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None
})
export class AppComponent  {
   name = 'Angular';
}

But it will be better to use styles on those components for which they were declared. 但是最好在声明了它们的那些组件上使用样式。

This is a working Stackblitz . 这是一个正在工作的Stackblitz

You were targeting <app-login> in the app.component.css file and styling it to have a fixed width and align it center. 您要在app.component.css文件中定位<app-login>并将其样式设置为具有固定宽度并使其居中对齐。 What you have to remember is that, Angular enforces emulated view encapsulation and also when you are using router, <app-login> may be changed to some random dynamic name at run time thereby making your css classes that you might have written in app.component.css ineffective. 您要记住的是,Angular强制执行了模拟视图封装,并且当您使用路由器时, <app-login>可能会在运行时更改为某些随机动态名称,从而使您可能已经在app中编写的css类成为可能。 component.css无效。

Its always a best practice to write styles for a component in its respective CSS file rather than the root components css file. 在组件各自的CSS文件中而不是在根组件css文件中编写组件样式始终是最佳实践。

Here is a changed Stackblitz 这是一个改变的Stackblitz

Here is the result: 结果如下: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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