2017-05-30 77 views
2

我试图在点击按钮上创建一个事件来激发另一个组件,如果再次单击它会减少组件(显示组件的一部分总是可见的).. 我知道这可以用[ngClass] ='隐藏'和一切在同一个组件中完成,但我不确定它是否是模块化方面的最佳方式。 在此先感谢

这里是我的html:

<div class="daydetail"> 
    <h1>Detail of the day</h1> 
    <button type="button" label="Click"(click)="display('my-displaychild')"></button> 
    <div>{{my-displaychild}}</div> 
</div> 

这里是我的组件:

import { DisplayChildComponent } from './displaychild.component'; 

export class AppliV2Component { 


    display(vid:DisplayChildComponent) { 
      console.log(DisplayChildComponent); 
    } 


} 
+2

使用ngIf指令 –

+0

@Maximus多亏我没想到ngIf容易:)我会尝试感谢您帮助 –

+0

没问题,让我知道如何去 –

回答

7

我想你应该保持简单与使用的*ngIf,您可以在布尔通值给子组件隐藏只有你想要的部分使用@Input修饰器

1.parent HTML

<div class="daydetail"> 
    <h1>Detail of the day</h1> 
    <button type="button" label="Click" (click)="toggleChild()"></button> 
    <div><child-component [showMePartially]="showVar"></child-component></div> 
</div> 

2.parent组件

export class AppliV2Component { 
showVar: boolean = true; 
toggleChild(){ 
this.showVar = !this.showVar; 
} 
} 

3.child组件

export class ChildComponent { 
@Input() showMePartially: boolean; 
// don't forget to import Input from '@angular/core' 
} 

4.child HTML

<div> 
<h1> this part is always visible</h1> 
</div> 

<div *ngIf="showMePartially"> 
<h1> this part will be toggled by the parent component button</h1> 
</div> 
+0

非常感谢我会试试这个,让你知道它是怎么回事! –

+1

@EmileCantero太棒了!但如果你只想显示部分子组件,我可以更新我的答案,告诉你如何做到这一点 –

+0

是的,让我看看我的朋友总是很好学:) –

0

我对产品的API。我列出了它们。用户可以将此项添加到购物车。

<div> 
    <ul class="list-group"> 
    <li *ngFor="let product of products" class="list-group-item"> 
    <button (click)="addToCart(product)" class="btn btn-xs btn-primary pull-right"> 
     <i class="glyphicon glyphicon-plus"></i> 
     Add To Cart 
    </button> 
    <h5><strong>{{product.productName}}</strong></h5> 
    <p> {{product.quantityPerUnit}}</p> 
    <h6>{{product.unitPrice}}</h6> 
    </li> 

方法是这样的。

addToCart(product:Product){ 
this.addedProduct=product.productName; 
this.notificationsService.success("Successfull",product.productName +" added to CART") 
    }