Angular组件如何基于内部变量控制自身显示隐藏
问题根因
@Output 是子组件向父组件传递事件的装饰器,无法直接绑定当前组件宿主元素的属性,所以你原有写法不生效。
可行方案
方案1:使用@HostBinding直接绑定组件宿主属性(推荐)
不需要修改父组件代码,完全满足col-6写在调用层级的要求:
- 在
app-streams组件的TS文件中引入HostBinding装饰器,绑定宿主的隐藏状态:
import { Component, HostBinding, OnInit } from '@angular/core'; @Component({ selector: 'app-streams', templateUrl: './streams.component.html' }) export class StreamsComponent implements OnInit { // 绑定宿主的hidden属性 @HostBinding('hidden') isHide: boolean = false; // 若担心[hidden]被CSS覆盖,可改用Bootstrap的d-none类绑定,优先级更高更稳定: // @HostBinding('class.d-none') isHide: boolean = false; ngOnInit(): void { // 调用你的服务,返回结果为空时把isHide设为true即可 this.yourService.getData().subscribe(res => { this.isHide = !res?.length; }) } }
- 父组件的调用代码不需要调整,保持原有写法即可:
<app-streams class="col-6"></app-streams>
方案2:通过@Output向父组件抛事件控制隐藏
如果需要父组件统一管控显示状态,可采用该方案:
- 子组件TS中定义事件发射器,服务返回结果为空时触发事件:
import { Component, Output, EventEmitter, OnInit } from '@angular/core'; @Component({ selector: 'app-streams', templateUrl: './streams.component.html' }) export class StreamsComponent implements OnInit { @Output() hideStateChange = new EventEmitter<boolean>(); ngOnInit(): void { this.yourService.getData().subscribe(res => { this.hideStateChange.emit(!res?.length); }) } }
- 父组件接收事件控制隐藏状态:
父组件TS中定义变量:
hideStream: boolean = false;
父组件模板修改为:
<app-streams class="col-6" [hidden]="hideStream" (hideStateChange)="hideStream = $event"></app-streams>
内容的提问来源于stack exchange,提问作者A. Nurb
相关产品推荐
相关产品推荐

