3

How may I add a string(css-class) to the parent Component? Different pages should be able to add a class to the container element.

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 Answer 1

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);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I may also want to share more informations like "display the header?" from child to parent component. Also the element must not be the parent in dom to access it with nativeElement.parentElement
Sure, you can always use a shared service for component communication angular.io/docs/ts/latest/cookbook/…
@SuttonY glad to hear :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.