从 Angular 中的 child 组件更改祖先的 class

Change class of ancestor from child component in Angular

我在我的应用程序中使用了 bootstrap container class,因为除了一个页面之外的所有页面都使用它,所以我将它放在 app.component.html 文件中:

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

我现在只有一个页面,但我想在其中使用 container-fluid 而不是 container。 child 组件有什么方法可以改变 class 吗?我尝试在 child 的 scss 中设置 !important 标签的边距,但这没有用。我也试过这个无济于事:

::ng-deep :host-context(.container) {
  margin: 0 !important;
}

回答

已更新以显示 Aviad P 评论中的路由解决方案。只需将其粘贴到 app.component.ts 文件中:

readonly #destroy$ = new Subject<void>()
fluid = false

constructor(private readonly router: Router) {
}

ngOnDestroy(): void {
    this.#destroy$.next()
    this.#destroy$.complete()
}

ngOnInit(): void {
    this.router.events.pipe(
        filter(x => x instanceof ActivationEnd),
        map(x => (x as ActivationEnd).snapshot.data),
        takeUntil(this.#destroy$)
    ).subscribe(x => {
        this.fluid = x.hasOwnProperty('fluid') ? !!x.fluid : false
    })
}

在你的 HTML 中,你会这样做:

<div [ngClass]="{'container': !fluid, 'container-fluid': fluid}">
    <router-outlet></router-outlet>
</div>

基本上,您需要一个服务作为路由组件和主要组件之间的通信通道。该服务将有一个变量,该变量将决定主要组件是 container 还是 container-fluid,并且每个组件都可以根据需要切换它。

container.service.ts

@Injectable({ providedIn: 'root' })
export class ContainerService {
  public fluid = false;
}

app.component.html

<div [class.container]="!svcContainer.fluid" [class.container-fluid]="svcContainer.fluid">
    <router-outlet></router-outlet>
</div>

app.component.ts, 'page-one.component.ts`, ... - 注入服务

  constructor(public svcContainer: ContainerService) {...}