Angular 2将一个字符串(css-class)添加到父Component

时间:2017-01-03 20:43:21

标签: angular angular2-directives

如何将字符串(css-class)添加到父组件? 不同的页面应该能够向容器元素添加一个类。

app.component.ts:

@Component({
  selector: 'app-root',
  template: `
        <div class="container {{ ADD HERE }}">
             <router-outlet></router-outlet>
        </div>
  `
})
export class AppComponent {
  title = 'app works!';
}

page1.component.ts:

@Component({
  template: `
      <p>I'm page 1!</p>
  `
})
export class Page1Component {
      containerClasses = "page-1";
}

1 个答案:

答案 0 :(得分:6)

@Component({
  template: `
      <p>I'm page 1!</p>
  `
})
export class APageComponent {
  constructor(private elRef:ElementRef) {
  }

  containerClasses = "page-1";

  ngAfterViewInit() {
    this.elRef.nativeElement.parentElement.classList.add(this.containerClasses);
  }
}