상위 구성 요소의 CSS 파일에서 하위 구성 요소를 스타일화하는 방법은 무엇입니까?
상위 구성 요소가 있습니다.
<parent></parent>
그리고 이 그룹에 하위 구성 요소를 입력합니다.
<parent>
<child></child>
<child></child>
<child></child>
</parent>
상위 템플릿:
<div class="parent">
<!-- Children goes here -->
<ng-content></ng-content>
</div>
하위 템플릿:
<div class="child">Test</div>
때부터parent
그리고.child
두 개의 개별 구성요소이며 스타일은 고유한 범위로 고정됩니다.
상위 구성요소에서 다음 작업을 시도했습니다.
.parent .child {
// Styles for child
}
그데그런..child
이 스일이않습니에 .child
구성 요소들.
사용해 보았습니다.styleUrls
함하여를 parent
를 일시트타스로.child
범위 문제를 해결하기 위한 구성 요소:
// child.component.ts
styleUrls: [
'./parent.component.css',
'./child.component.css',
]
하지만 그것은 도움이 되지 않았고, 또한 다른 방법으로 그것을 가져옴으로써 시도했습니다.child
를 스일시를에추가트타로 변환합니다.parent
하지만 그것도 도움이 되지 않았습니다.
그러면 부모 구성요소에 포함된 자식 구성요소의 스타일은 어떻게 설정합니까?
업데이트 - 최신 방법
피할 수 있다면 하지 마세요.데본 산스가 논평에서 지적했듯이:이 기능은 사용되지 않을 가능성이 기능은 더 이상 사용되지 않습니다.
마지막 업데이트
Angular 4.3.0부터 지금까지(Angular 12.x) 모든 피어싱 CSS 결합기는 사용되지 않았습니다.Angular 팀은 아래와 같이 새로운 조합을 도입했습니다.
데모: https://plnkr.co/edit/RBJIszu14o4svHLQt563?p=preview
styles: [
`
:host { color: red; }
:host ::ng-deep parent {
color:blue;
}
:host ::ng-deep child{
color:orange;
}
:host ::ng-deep child.class1 {
color:yellow;
}
:host ::ng-deep child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
올드웨이
사용할 수 있습니다.encapsulation mode
및/는piercing CSS combinators >>>, /deep/ and ::shadow
작동 예: http://plnkr.co/edit/1RBDGQ?p=preview
styles: [
`
:host { color: red; }
:host >>> parent {
color:blue;
}
:host >>> child{
color:orange;
}
:host >>> child.class1 {
color:yellow;
}
:host >>> child.class2{
color:pink;
}
`
],
template: `
Angular2 //red
<parent> //blue
<child></child> //orange
<child class="class1"></child> //yellow
<child class="class2"></child> //pink
</parent>
`
사하면안됩다니를 사용하면 안 .::ng-deep
더 이상 사용되지 않습니다.Angular(각도)에서 부모에서 자식 구성요소의 스타일을 변경하는 올바른 방법은 다음을 사용하는 것입니다(아래 경고를 읽고 의미를 이해하십시오).
import { ViewEncapsulation } from '@angular/core';
@Component({
....
encapsulation: ViewEncapsulation.None
})
그런 다음 ::ng-deep에서 필요 없이 구성 요소의 CSS를 수정할 수 있습니다.
.mat-sort-header-container {
display: flex;
justify-content: center;
}
경고: 이렇게 하면 이 구성 요소에 대해 작성한 모든 CSS 규칙이 글로벌하게 됩니다.
CSS의 범위를 이 구성 요소와 그의 자식으로만 제한하려면 구성 요소의 맨 위 태그에 CSS 클래스를 추가하고 이 태그 안에 CSS를 넣으십시오.
템플릿:
<div class='my-component'>
<child-component class="first">First</child>
</div>,
Scss 파일:
.my-component {
// All your css goes in there in order not to be global
}
업데이트 3:
::ng-deep
또한 더 이상 이 작업을 수행해서는 안 됩니다.이것이 부모 구성요소에서 자식 구성요소의 스타일을 재정의해야 하는 항목에 어떤 영향을 미치는지는 명확하지 않습니다.라이브러리 구성요소에서 스타일을 재정의해야 하는 라이브러리로서 이 기능이 어떤 영향을 미칠까요?
이에 대한 통찰력이 있으면 댓글을 달아주세요.
업데이트 2:
때부터/deep/
다른 모든 그림자 피어싱 선택기는 이제 더 이상 사용되지 않습니다. 감소 도각 감소감::ng-deep
더 광범위한 호환성을 위해 대신 사용해야 합니다.
업데이트:
Angular-CLI를 ./deep/
에 >>>
그렇지 않으면 작동하지 않을 것입니다.
원본:
Angular2의 Github 페이지로 이동하여 "style"을 무작위로 검색한 결과 다음과 같은 질문을 발견했습니다.각도 2 - 내부HTML 스타일
에 추가된 것을 사용하라는 말이 있었습니다.2.0.0-beta.10
,>>>
그리고.::shadow
선택기
(>>) (및 동등한/깊이/)와 ::sys는 2.0.0-208.10에 추가되었습니다.이들은 섀도 DOM CSS 결합기(더 이상 사용되지 않음)와 유사하며 캡슐화에서만 작동합니다.보기 캡슐화.Angular2에서 기본값인 에뮬레이트됩니다.View Encapsulation에서도 작동할 수 있습니다.없음. 그러나 필요하지 않기 때문에 무시됩니다.이러한 결합기는 구성요소 간 스타일링을 위한 고급 기능이 지원되기 전까지는 중간 솔루션에 불과합니다.
간단히 수행할 수 있는 그대로:
:host >>> .child {}
parent
의 스타일시트 파일이 문제를 해결했습니다.위의 인용문에 명시된 바와 같이, 이 솔루션은 고급 구성 요소 간 스타일링이 지원될 때까지는 중간 수준에 불과합니다.
Angular 구성 요소는 외부에서 사용할 수 있는 항목을 명시적으로 선언해야 하는 자체 포함 엔티티이므로 부모 구성 요소의 자식 구성 요소에 대한 CSS 규칙을 작성하면 안 됩니다.나중에 하위 레이아웃이 변경되면 다른 구성 요소의 SCSS 파일에 흩어져 있는 하위 구성 요소의 스타일이 쉽게 손상되어 스타일이 매우 취약해질 수 있습니다. 그거야.ViewEncapsulation
CSS의 경우를 위한 것입니다.그렇지 않으면 개체 지향 프로그래밍에서 다른 클래스의 개인 필드에 값을 할당할 수 있습니다.
따라서 하위 호스트 요소에 적용할 수 있는 클래스 집합을 정의하고 하위 호스트 요소에 대해 자식이 응답하는 방식을 구현해야 합니다.
기술적으로 다음과 같이 수행할 수 있습니다.
// child.component.html:
<span class="label-1"></span>
// child.component.scss:
:host.child-color-black {
.label-1 {
color: black;
}
}
:host.child-color-blue {
.label-1 {
color: blue ;
}
}
// parent.component.html:
<child class="child-color-black"></child>
<child class="child-color-blue"></child>
다말해서, 은신당을 합니다.:host
자식 구성 요소 자체에서 가능한 자식 스타일을 정의하기 위해 Angular + CSS 클래스 집합에서 제공하는 유사 선택기입니다.그런 다음 미리 정의된 클래스를 다음에 적용하여 외부에서 해당 스타일을 트리거할 수 있습니다.<child>
호스트 요소.
슬프게도 /deep/selector는 사용되지 않는 것 같습니다(적어도 Chrome에서는) https://www.chromestatus.com/features/6750456638341120 .
간단히 말해서, 자녀 구성 요소가 동적으로 스타일을 설정하도록 하는 것 외에는 (현재) 장기적인 해결책이 없는 것으로 보입니다.
다음을 통해 스타일 객체를 자식에게 전달하고 적용할 수 있습니다.
<div [attr.style]="styleobject">
또는 특정 스타일이 있는 경우 다음과 같은 것을 사용할 수 있습니다.
<div [style.background-color]="colorvar">
이와 관련된 더 많은 논의: https://github.com/angular/angular/issues/6511
같은 문제가 있었기 때문에 scss/sass와 함께 angular2-cli를 '>>> 대신 '/deep/'를 사용하는 경우 마지막 선택기는 아직 지원되지 않습니다(그러나 CSS에서는 잘 작동합니다).
실제 하위 구성 요소보다 더 많은 대상을 지정하려면 다음을 수행해야 합니다.이렇게 하면 다른 하위 구성 요소가 동일한 클래스 이름을 공유하더라도 영향을 받지 않습니다.
플런커: https://plnkr.co/edit/ooBRp3ROk6fbWPuToytO?p=preview
예:
import {Component, NgModule } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `
<div>
<h2>I'm the host parent</h2>
<child-component class="target1"></child-component><br/>
<child-component class="target2"></child-component><br/>
<child-component class="target3"></child-component><br/>
<child-component class="target4"></child-component><br/>
<child-component></child-component><br/>
</div>
`,
styles: [`
/deep/ child-component.target1 .child-box {
color: red !important;
border: 10px solid red !important;
}
/deep/ child-component.target2 .child-box {
color: purple !important;
border: 10px solid purple !important;
}
/deep/ child-component.target3 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this won't work because the target component is spelled incorrectly */
/deep/ xxxxchild-component.target4 .child-box {
color: orange !important;
border: 10px solid orange !important;
}
/* this will affect any component that has a class name called .child-box */
/deep/ .child-box {
color: blue !important;
border: 10px solid blue !important;
}
`]
})
export class App {
}
@Component({
selector: 'child-component',
template: `
<div class="child-box">
Child: This is some text in a box
</div>
`,
styles: [`
.child-box {
color: green;
border: 1px solid green;
}
`]
})
export class ChildComponent {
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App, ChildComponent ],
bootstrap: [ App ]
})
export class AppModule {}
이것이 도움이 되길 바랍니다!
코드 매트릭스
사실 선택지가 하나 더 있습니다.어느 쪽이 안전한가요?View Encapsulation을 사용할 수 있습니다.모든 구성요소 스타일을 태그(선택기라고도 함)에 넣습니다.하지만 어쨌든 항상 일부 글로벌 스타일과 캡슐화된 스타일을 선호합니다.
수정된 Denis Rybalka의 예는 다음과 같습니다.
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'parent',
styles: [`
parent {
.first {
color:blue;
}
.second {
color:red;
}
}
`],
template: `
<div>
<child class="first">First</child>
<child class="second">Second</child>
</div>`,
encapsulation: ViewEncapsulation.None,
})
export class ParentComponent {
constructor() { }
}
/deep/, >>>, ::ng-deep는 모두 사용되지 않습니다.가장 좋은 방법은 다음을 어린이 구성 요소 스타일링에 사용하는 것입니다.
:host-context(.theme-light) h2 {
background-color: #eef;
}
이것은 어린이 구성 요소의 조상에 있는 테마 라이트를 찾습니다.다음 문서를 참조하십시오. https://angular.io/guide/component-styles#host-context
각도에서 이를 달성하기 위한 몇 가지 옵션이 있습니다.
딥 CSS 실렉터를 사용할 수 있습니다.
:host >>> .childrens {
color: red;
}
또한 뷰 캡슐화를 기본값으로 Emulated로 설정하지만 Shadow DOM 네이티브 브라우저 구현을 사용하는 Native로 쉽게 변경할 수 있습니다. 이 경우 사용하지 않도록 설정하면 됩니다.
예:`
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'parent',
styles: [`
.first {
color:blue;
}
.second {
color:red;
}
`],
template: `
<div>
<child class="first">First</child>
<child class="second">Second</child>
</div>`,
encapsulation: ViewEncapsulation.None,
})
export class ParentComponent {
constructor() {
}
}
하위 구성 요소 코드에 액세스할 수 있는 경우 @INPUT 변수를 전달하는 것이 훨씬 더 깔끔합니다.
부모가 아이에게 자신의 외모 상태가 어떠해야 하는지를 알려주고, 아이가 그 상태를 어떻게 표시할지를 결정한다는 생각입니다.멋진 건축물입니다.
SCSS 방법:
.active {
::ng-deep md-list-item {
background-color: #eee;
}
}
더 나은 방법: - 사용selected
변수:
<md-list>
<a
*ngFor="let convo of conversations"
routerLink="/conversations/{{convo.id}}/messages"
#rla="routerLinkActive"
routerLinkActive="active">
<app-conversation
[selected]="rla.isActive"
[convo]="convo"></app-conversation>
</a>
</md-list>
오늘(Angular 9) 현재 Angular는 Shadow DOM을 사용하여 구성요소를 사용자 정의 HTML 요소로 표시합니다.이러한 사용자 정의 요소를 스타일화하는 한 가지 우아한 방법은 사용자 정의 CSS 변수를 사용하는 것일 수 있습니다.다음은 일반적인 예입니다.
class ChildElement extends HTMLElement {
constructor() {
super();
var shadow = this.attachShadow({mode: 'open'});
var wrapper = document.createElement('div');
wrapper.setAttribute('class', 'wrapper');
// Create some CSS to apply to the shadow dom
var style = document.createElement('style');
style.textContent = `
/* Here we define the default value for the variable --background-clr */
:host {
--background-clr: green;
}
.wrapper {
width: 100px;
height: 100px;
background-color: var(--background-clr);
border: 1px solid red;
}
`;
shadow.appendChild(style);
shadow.appendChild(wrapper);
}
}
// Define the new element
customElements.define('child-element', ChildElement);
/* CSS CODE */
/* This element is referred as :host from the point of view of the custom element. Commenting out this CSS will result in the background to be green, as defined in the custom element */
child-element {
--background-clr: yellow;
}
<div>
<child-element></child-element>
</div>
위의 코드에서 알 수 있듯이, 우리는 Angular가 모든 구성 요소에 대해 하는 것처럼 사용자 정의 요소를 만든 다음 사용자 정의 요소의 섀도 루트 내에서 배경색을 담당하는 변수를 전역 범위에서 재정의합니다.
Angular 앱에서 이것은 다음과 같을 수 있습니다.
parent.component.scss
child-element {
--background-clr: yellow;
}
child-interval.component.scss
:host {
--background-clr: green;
}
.wrapper {
width: 100px;
height: 100px;
background-color: var(--background-clr);
border: 1px solid red;
}
이를 위해 제가 선호하는 것은 다음과 같습니다.
사용하다@Component
호스트 요소에 CSS 클래스를 추가하고 캡슐화를 없음으로 설정합니다. 다음 합니다.style.css.scss
이것은 우리가 우리 반의 범위 내에서 우리 자신과 우리 아이들에게만 영향을 미칠 스타일을 선언할 수 있게 해줄 것입니다.
@Component({
selector: 'my-component',
templateUrl: './my-component.page.html',
styleUrls: ['./my-component.page.scss'],
host: {
class: 'my-component-class'
},
encapsulation: ViewEncapsulation.None
})
다음 CSS(my-component.page.scss)와 함께 사용합니다.
// refer ourselves so we are allowed to overwrite children but not global styles
.my-component-class {
// will effect direct h1 nodes within template and all h1 elements within child components of the
h1 {
color: red;
}
}
// without class "scope" will affect all h1 elements globally
h1 {
color: blue;
}
빠른 대답은 여러분이 이런 일을 해서는 안 된다는 것입니다.구성요소 캡슐화를 해제하고 자체 구성요소로부터 얻을 수 있는 이점을 훼손합니다.하위 구성 요소에 프롭 플래그를 전달하는 것을 고려하면 필요한 경우 다른 렌더링 방법이나 다른 CSS를 적용하는 방법을 스스로 결정할 수 있습니다.
<parent>
<child [foo]="bar"></child>
</parent>
Angular는 부모로부터 아이들의 스타일에 영향을 미치는 모든 방법을 비난하고 있습니다.
https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep
요소에 하구요서에요클래할를스다당사면음다용니합을을 .@Input
자식 구성 요소에 있는 문자열을 템플릿 내부의 식으로 사용합니다.다음은 코드베이스 전체에서 이미 사용된 방법에 영향을 주지 않고 공유 부트스트랩 로드 단추 구성 요소에서 아이콘과 단추 유형을 변경하기 위해 수행한 작업의 예입니다.
app-loading-button.component.component(하위)
<button class="btn {{additionalClasses}}">...</button>
app-loading-button.component.ts
@Input() additionalClasses: string;
부모님.
<app-loading-button additionalClasses="fa fa-download btn-secondary">...</app-loading-button>
저도 이 문제가 있었고 사용되지 않는 솔루션을 사용하고 싶지 않았기 때문에 결국 다음과 같이 되었습니다.
부모로서
<dynamic-table
ContainerCustomStyle='width: 400px;'
>
</dynamic-Table>
하위 구성 요소
@Input() ContainerCustomStyle: string;
html div의 자식에서.
<div class="container mat-elevation-z8"
[style]='GetStyle(ContainerCustomStyle)' >
암호로
constructor(private sanitizer: DomSanitizer) { }
GetStyle(c) {
if (isNullOrUndefined(c)) { return null; }
return this.sanitizer.bypassSecurityTrustStyle(c);
}
예상과 같은 작업이므로 사용을 중단해서는 안 됩니다;)
인터넷이 업데이트되면서 해결책을 찾았습니다.
먼저 몇 가지 주의 사항.
- 그래도 하지 마.명확하게 하기 위해, 저는 당신이 그것들을 스타일링하도록 허용하는 어린이 구성요소를 계획하지 않을 것입니다.SOC. 구성요소 설계자가 이를 허용하기를 원한다면 더욱 강력한 성능을 참조하십시오.
- 만약 당신의 아이가 어둠 속에 살지 않는다면, 이것은 당신에게 효과가 없을 것입니다.
- 섀도돔을 사용할 수 없는 브라우저를 지원해야 하는 경우에도 이 기능이 작동하지 않습니다.
먼저 하위 구성 요소의 캡슐화를 섀도로 표시하여 실제 섀도로 렌더링합니다.둘째, 부모 스타일을 허용할 요소에 요소 특성을 추가합니다.부모의 구성요소 스타일시트에서 ::part() 메서드를 사용하여 액세스할 수 있습니다.
바닐라 않으며, 이은바만 CSS도 . 화려하지도 않고, 심지어 필요하지도 않습니다.!important
아이를 수정할 수는 없는 것 같고, 그렇지 않으면 답이 더 간단해서 혹시나 해서 마지막에 그 답을 넣었습니다.
요소를 때하며, 를라러리에서미만용사소 CSS이할것며이하다필요, 발자지습니았않하제공것어도개떤들은브때를 제공하지 않았습니다.class
입력 변수 ::ng-deep
더 이상 사용하지 않습니다.encapsulation: ViewEncapsulation.None
구성 요소의 모든 CSS를 전역으로 전환합니다.그래서 이것들 중 어느 것도 사용하지 않는 간단한 해결책이 있습니다.
사실, 우리는 CSS가 아이들에게 도달하기 위해서는 글로벌 스타일이 필요합니다.그래서 우리는 그냥 스타일을 넣을 수 있습니다.styles.css
CSS 파일에 할 수도 .styles
을 의열로 표시합니다.angular.json
유일한 문제는 다른 요소를 대상으로 하지 않도록 특정 선택기가 필요하다는 것입니다.이 방법은 매우 간단합니다. HTML에 고유한 클래스 이름을 추가하기만 하면 됩니다. 클래스 이름에 상위 구성 요소의 이름을 사용하여 고유함을 확인하는 것이 좋습니다.
상위 구성 요소
<child class="child-in-parent-component"></child>
아이의 모든 버튼의 배경색을 변경하고 싶다고 가정해 보겠습니다. 스타일이 우선되도록 하려면 정확한 특수성을 확보해야 합니다.우리는 이것을 할 수 있습니다.!important
우리의 모든 속성 옆에 있지만, 더 나은 방법은 우리의 선택자가 충분히 구체적일 때까지 클래스 이름을 반복하는 것입니다. 몇 번의 시도가 필요할 수도 있습니다.그런 식으로, 필요한 경우 다른 사람이 이 CSS를 다시 재정의할 수 있습니다.
전역 스타일 파일
.child-in-parent-component.child-in-parent-component.child-in-parent-component
button {
background-color: red;
}
좋아요.!important
하지 않음장되지않음)
.child-in-parent-component button {
background-color: red !important;
}
하위 구성 요소를 수정할 수 있는지 여부
구성 요소에 입력 변수를 추가하고 Angular's를 사용하기만 하면 됩니다.ngStyle
을 지정할 수 .여러 변수를 추가하여 구성요소의 여러 영역에 스타일을 지정할 수 있습니다.
하위 구성 요소
type klass = { [prop: string]: any } | null;
@Component({...})
export class ChildComponent {
@Input() containerClass: klass = null;
@Input() pClass: klass = null;
...
}
<div [ngStyle]="containerClass">
<p [ngStyle]="pClass">What color will I be?</p>
</div>
상위 구성 요소
<child
[containerClass]="{ padding: '20px', 'background-color': 'black' }"
[pClass]="{ color: 'red' }"
>
</child>
동적 스타일을 사용하여 구성요소를 작성하는 방법입니다.많은 사전 제작된 구성 요소에는 유사한 입력 변수가 있습니다.
이것은 나에게 효과가 있었습니다.
상위 구성 요소:
<child-component [styles]="{width: '160px', borderRadius: '16px'}" >
</child-component>
angular.io/guide/component-styles 에서 다음과 같이 언급하고 있으므로 보다 명확하게 하기 위해 예를 제안합니다.
섀도 피어싱 하위 조합은 더 이상 사용되지 않으며 주요 브라우저 및 도구에서 지원이 제거되고 있습니다.따라서 Angular에서 지원을 중단할 계획입니다(/deep/, >> 및 ::ng-deep의 3가지 모두에 대해).그때까지는 ::ng-deep가 도구와의 광범위한 호환성을 위해 선호되어야 합니다.
app.component.scss
를 *.scss
필요한 경우에는 _colors.scss
에는 몇 가지 공통 색상 값이 있습니다.
$button_ripple_red: #A41E34;
$button_ripple_white_text: #FFF;
모든 구성 요소에 규칙 적용
에 모든버가 있습니다.btn-red
수업은 스타일이 될 것입니다.
@import `./theme/sass/_colors`;
// red background and white text
:host /deep/ button.red-btn {
color: $button_ripple_white_text;
background: $button_ripple_red;
}
단일 구성 요소에 규칙 적용
에 모든버가 있습니다.btn-red
을 가르치다.app-login
구성요소가 스타일화됩니다.
@import `./theme/sass/_colors`;
/deep/ app-login button.red-btn {
color: $button_ripple_white_text;
background: $button_ripple_red;
}
Angular 밖에서 해결했습니다.자녀에게 가져올 공유 SC를 정의했습니다.
shared.scss
%cell {
color: #333333;
background: #eee;
font-size: 13px;
font-weight: 600;
}
child.scss
@import 'styles.scss';
.cell {
@extend %cell;
}
제가 제안한 접근법은 OP가 질문한 문제를 해결하는 방법입니다.여러 번 언급했듯이 ::ng-deep, :ng-host는 감가상각될 것이며 캡슐화를 비활성화하는 것은 코드 유출의 너무 많은 것이라고 생각합니다.
'parent'는 부모의 클래스 이름이고 'child'는 자식의 클래스 이름입니다.
.parent .child{
//css definition for child inside parent components
}
이 형식을 사용하여 CSS 형식을 '부모' 내부의 '자녀' 구성 요소로 정의할 수 있습니다.
언급URL : https://stackoverflow.com/questions/36527605/how-to-style-child-components-from-parent-components-css-file
'programing' 카테고리의 다른 글
PostgreSQL에서 상속된 테이블을 사용해야 하는 경우 (0) | 2023.05.02 |
---|---|
Postgres SELECT에서 열을 연결하는 방법은 무엇입니까? (0) | 2023.05.02 |
OS X에서 $PATH(.bash_profile)를 어떻게 편집합니까? (0) | 2023.04.27 |
Angular HttpClient에서 오류를 감지하는 중 (0) | 2023.04.27 |
시스템 트레이에 대한 앱 최소화 (0) | 2023.04.27 |