我在一个触发功能的组件上有按钮:
<button class="btn-main" (click)="hideElement()"></button>
在弹出窗口的另一个组件中(没有父子连接),我有3个像这样的div
<div class="element1"></div>
当我点击父级中的按钮时,我希望隐藏一个(设置具有可见性的类:隐藏)。当我用那个按钮打开弹出框时,如何隐藏该div?
答案 0 :(得分:0)
:
people$students
子组件中的:
people$teachers
在父母的:
<div class="element1" #element1 ></div>
答案 1 :(得分:0)
方法1 - 亲子关系
您可以使用hideDiv
属性隐藏或显示子组件中的div,并使该属性可用于与@Input
装饰器进行数据绑定。该属性可以直接切换visibility
样式或将类应用于div:
@Component({
selector: 'child-component',
template: `
<div></div>
<div [class.hiddenClass]="hideDiv"></div>
<div [style.visibility]="hideDiv ? 'hidden' : 'visible'"></div>
<div></div>
`,
styles: [`.hiddenClass { visibility: hidden; }`]
})
export class ChildComponent {
@Input() hideDiv = false;
}
然后,当您单击父组件中的按钮时,您将使用数据绑定对其进行修改:
@Component({
selector: 'parent-component',
template: `
<button (click)="hideChildDiv = !hideChildDiv">Toggle div visibility</button>
<child-component [hideDiv]="hideChildDiv" ></child-component>
`
})
export class ParentComponent {
hideChildDiv = false;
}
您可以在this stackblitz中测试代码。
方法2 - 具有服务的两个组件之间的通信
您可以使用服务允许两个单独的组件相互通信或共享一些信息。有关演示,请参阅this stackblitz。
<强>服务强>:
import { Injectable } from "@angular/core"
@Injectable()
export class VisibilityService {
hideDiv = false;
}
父组件:
@Component({
selector: 'app-root',
template: `
<child1></child1>
<child2></child2>
`
})
export class AppComponent {
}
Child1组件:
import { VisibilityService } from "./visibility.service";
@Component({
selector: 'child1',
template: `
<button (click)="hideDiv = !hideDiv">Toggle div visibility</button>
`
})
export class Child1Component {
public get hideDiv(): boolean {
return this.visibilityService.hideDiv;
}
public set hideDiv(value: boolean) {
this.visibilityService.hideDiv = value;
}
constructor(private visibilityService: VisibilityService) { }
}
Child2组件:
import { VisibilityService } from "./visibility.service";
@Component({
selector: 'child2',
template: `
<div class="div1"></div>
<div class="div1" [class.hiddenClass]="hideDiv"></div>
<div class="div1"></div>
<div class="div1" [style.visibility]="hideDiv ? 'hidden' : 'visible'"></div>
<div class="div1"></div>
`
})
export class Child2Component {
public get hideDiv(): boolean {
return this.visibilityService.hideDiv;
}
constructor(private visibilityService: VisibilityService) { }
}
<强>模块强>:
...
import { AppComponent } from './app.component';
import { Child1Component } from './child1.component';
import { Child2Component } from './child2.component';
import { VisibilityService } from "./visibility.service";
@NgModule({
declarations: [
AppComponent,
Child1Component,
Child2Component
],
providers: [
VisibilityService
],
...
})
export class AppModule { }