【发布时间】:2017-05-11 01:40:24
【问题描述】:
我想通过使用位于另一个组件中的按钮来显示和隐藏一个元素。
所以我有一个仪表板,里面有很多房间和一个标题。
带有 app-header 和 app-chamber 的 DashboardComponent 的 HTML:
<app-header></app-header>
<div class="container">
<div class="row">
<app-chamber [kamers]="kamers"></app-chamber>
</div>
</div>
我的 ChamberComponent 中有这个带有 *ngIf 的 HTML:
<div class="col-sm-6 col-md-4 col-lg-3 cardcol" *ngFor="let kamer of kamers; let i = index">
<md-card class="chamber wit" *ngIf="kamer.patient == null">
<p *ngIf="showId">{{kamer.id}}</p>
</md-card>
</div>
在 HeaderComponent 我有一个需要显示和隐藏元素的按钮:
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
@Input() aList;
dashboardComponent:DashboardComponent;
chamberComponent:ChamberComponent;
constructor(dashboardComponent: DashboardComponent, chamberComponent:ChamberComponent) {
this.dashboardComponent = dashboardComponent;
this.chamberComponent = chamberComponent;
}
ngOnInit() {
}
// THIS GETS CALLED BY A BUTTON CLICK
toggleId(){
this.chamberComponent.toggleId();
}
}
然后是我的 ChamberComponent 代码:
@Component({
selector: 'app-chamber',
templateUrl: './chamber.component.html',
styleUrls: ['./chamber.component.css']
})
export class ChamberComponent implements OnInit {
@Input() kamers;
showId:boolean;
constructor() {
this.showId=false;
}
ngOnInit() {
}
toggleId = () => {
this.showId = !this.showId;
}
}
所以当我点击按钮时,值会发生变化(我已经在控制台中记录了这个)但视图没有更新..
当我在 ChamberComponent 中放置一个调用 toggleId() 函数的按钮时,视图确实会收到更新,并且元素会显示或隐藏。
但我需要从标题上的按钮切换它。
【问题讨论】:
-
副本是关于回调范围内的“this”。但是,我的代码应该根据该示例工作。 this.showId 不工作..
-
如果完全没有显示或隐藏,并且您没有其他内容,您确定满足
*ngIf="kamer.patient == null"的条件吗? -
这就是问题所在,这应该非常重要地添加到问题中,因为它是非常相关的信息!所以请将所有相关代码放在帖子中! :)
-
我已经更新了问题,谢谢!
标签: angular angular-ng-if