我在一个触发功能的一个组件上有按钮:
<button class="btn-main" (click)="hideElement()"></button>
在弹出弹出的另一个组件中(没有亲子连接(,我有3个Divs
<div class="element1"></div>
我希望在父母中单击按钮时隐藏一个人(设置具有可见性:隐藏的类(。使用该按钮打开弹出窗口时,我该如何隐藏该div?
在儿童模板中:
<div class="element1" #element1 ></div>
在儿童组件中:
@ViewChild('element1') element1: ElementRef;
在父母中:
@ViewChild(ChildComponent) child: ChildComponent;
constructor(private renderer: Renderer2) {}
hideElement() {
this.renderer.setStyle(child.element1 , 'visibility' , 'hidden');
}
方法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;
}
您可以在中测试代码此stackblitz 。
方法2-服务与服务的两个组件之间的通信
您可以使用服务允许两个单独的组件相互通信或共享一些信息。有关演示,请参见此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 component :
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 component :
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 { }