这个问题很简单,但我无法摆脱它。
我在父模板中有一个<header>
,当通过路由模块显示子模板时,我需要它消失。我期望在header标签中添加一个类,以便我可以通过CSS隐藏它。这就是我所拥有的:
的 app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app',
template: `
<header [class.hidden]="hide">
<h1>My App</h1>
<ul>
<li><a href="/home"></a></li>
<li><a href="/showoff"></a></li>
</ul>
</header>
<router-outlet></router-outlet>
`
})
export class AppComponent {
hide = false; // <-- This is what I need to change in child component
}
应用-routing.module.ts
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './welcome.component';
import { ShowOffComponent } from './show.off.component';
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'showoff', component: ShowOffComponent },
];
export const AppRouting = RouterModule.forRoot(routes, {
useHash: true
});
show.offf.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-showoff',
template: `
<h2>Show Off</h2>
<div>Some contents...</div>
`
})
export class ShowOffComponent {
hide = true; // <-- Here is the problem.
// I don't have any idea how to reach parent variables.
}
答案 0 :(得分:8)
您可以使用output emitter
在您的子组件中
import { Component } from '@angular/core';
@Component({
selector: 'app-showoff',
template: `
<h2>Show Off</h2>
<div>Some contents...</div>
`
})
export class ShowOffComponent {
@Output() onHide = new EventEmitter<boolean>();
setHide(){
this.onHide.emit(true);
}
}
在父母中,
export class AppComponent {
hide = false;
onHide(val: boolean) {
this.hide=val;
}
}
答案 1 :(得分:3)
在app.component.ts
中,您可以检查自己的网址并设置hide
变量值,如下所示:
import { Component } from '@angular/core';
import { Router, NavigationStart } from '@angular/router';
@Component({
selector: 'app',
template: `
<header [class.hidden]="hide">
<h1>My App</h1>
<ul>
<li><a href="/home"></a></li>
<li><a href="/showoff"></a></li>
</ul>
</header>
<router-outlet></router-outlet>
`
})
export class AppComponent {
hide = false; // <-- This is what I need to change in child component
constructor(private router: Router){}
public ngOnInit() {
this.router.events.subscribe((events) => {
if (events instanceof NavigationStart) {
if (events.url === '/' || events.url === '/home') {
this.hide = false;
} else {
this.hide = true;
}
}
});
}
}
答案 2 :(得分:2)
我最近在Angular 6中遇到了相同的现象。
我想访问和更改属于父组件或祖父母组件的变量。参见下图。我想访问和更改属于吉姆(汤姆的孩子)和萨拉(汤姆的孙子)的汤姆所属的变量。
可能还有其他解决方案,但是我用来克服此问题的方法是使用ViewContainerRef
。我必须将ViewContainerRef
注入到子组件的构造函数中,我需要访问父组件并遍历父节点(或多个节点)以找到父变量。
注入构造函数,
constructor(private viewContainerRef: ViewContainerRef) { }
访问并遍历到父节点,
getParentComponent() {
return this.viewContainerRef[ '_data' ].componentView.component.viewContainerRef[ '_view' ].component
}
我已经用上图中给出的方案制作了一个StackBlitz示例。
https://stackblitz.com/edit/angular-comms
希望有人会发现这很有用。
谢谢。