Programing

Angular 2 : 컴포넌트의 호스트 요소를 어떻게 스타일링합니까?

crosscheck 2020. 5. 27. 21:42
반응형

Angular 2 : 컴포넌트의 호스트 요소를 어떻게 스타일링합니까?


Angular 2에는 my-comp라는 구성 요소가 있습니다.

<my-comp></my-comp>

Angular 2 에서이 구성 요소의 호스트 요소를 어떻게 스타일링합니까?

Polymer에서는 ": host"선택기를 사용합니다. Angular 2에서 시도했지만 작동하지 않습니다.

:host {
  display: block;
  width: 100%;
  height: 100%;
}

또한 구성 요소를 선택기로 사용하려고 시도했습니다.

my-comp {
  display: block;
  width: 100%;
  height: 100%;
}

두 방법 모두 작동하지 않는 것 같습니다.

감사.


버그가 있었지만 그 동안 수정되었습니다. :host { }지금은 잘 작동합니다.

또한 지원됩니다

  • :host(selector) { ... }selector호스트 요소에서 속성, 클래스 등을 일치 시키기 위해
  • :host-context(selector) { ... }selector부모 구성 요소의 요소, 클래스 등을 일치 시키기 위해

  • selector /deep/ selectorselector >>> selector요소 경계에서 스타일이 일치하도록 (별칭 은 SASS와 함께 작동하지 않음)

    • 업데이트 : SASS가 더 이상 사용되지 않습니다 /deep/. SASS와 호환되는 대체품으로
      Angular (TS 및 Dart)가 추가 ::ng-deep되었습니다.

    • UPDATE2 : ::slotted ::slotted 이제 모든 새 브라우저에서 지원되며`ViewEncapsulation.ShadowDom https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted 와 함께 사용할 수 있습니다

Angular 2 구성 요소에 외부 CSS 스타일로드를 참조하십시오.

/deep/하고 >>>있다 영향을받지 크롬에서 사용되지 않습니다 같은 선택 콤비에 의해.
Angular는 그것들을 에뮬레이트 (다시 쓰기)하므로이를 지원하는 브라우저에 의존하지 않습니다.

이것이 기본 섀도우 DOM을 활성화하고 브라우저 지원에 의존하는 이유 /deep/>>>작동하지 않는 이유 ViewEncapsulation.Native입니다.


구성 요소 요소의 스타일을 지정하는 방법에 대한 해결책을 찾았습니다. 작동 방식에 대한 문서를 찾지 못했지만 다음과 같이 'host'속성 아래에서 속성 값을 구성 요소 지시문에 넣을 수 있습니다.

@Component({
    ...
    styles: [`
      :host {
        'style': 'display: table; height: 100%',
        'class': 'myClass'
      }`
})
export class MyComponent
{
    constructor() {}

    // Also you can use @HostBinding decorator
    @HostBinding('style.background-color') public color: string = 'lime';
    @HostBinding('class.highlighted') public highlighted: boolean = true;
}

업데이트 : Günter Zöchbauer가 언급했듯이 버그가 있었고 이제 CSS 파일에서도 다음과 같이 호스트 요소의 스타일을 지정할 수 있습니다.

:host{ ... }

이 문제를 확인하십시오 . 새로운 템플릿 사전 컴파일 로직 이 구현 되면 버그가 해결 될 것이라고 생각합니다 . 지금은 템플릿을 래핑 <div class="root">하고 스타일 을 지정하는 것이 최선이라고 생각합니다 div.

@Component({ ... })
@View({
  template: `
    <div class="root">
      <h2>Hello Angular2!</h2>
      <p>here is your template</p>
    </div>
  `,
  styles: [`
    .root {
      background: blue;
    }
  `],
   ...
})
class SomeComponent {}

참조 이 plunker을


적용하려는 일반적인 스타일이 있으면 Component에서 .class를 호스트 요소에 추가 할 수 있습니다.

export class MyComponent{
     @HostBinding('class') classes = 'classA classB';

For anyone looking to style child elements of a :host here is an example of how to use ::ng-deep

:host::ng-deep <child element>

e.g :host::ng-deep span { color: red; }

As others said /deep/ is deprecated


Try the :host > /deep/ :

Add the following to the parent.component.less file

:host {
    /deep/ app-child-component {
       //your child style
    }
}

Replace the app-child-component by your child selector

참고URL : https://stackoverflow.com/questions/32853924/angular-2-how-to-style-host-element-of-the-component

반응형