角度隐藏和显示图像取决于所选的传递参数

时间:2018-01-09 15:07:56

标签: javascript angular

我有一个下拉列表:

<ul class="dropdown-menu">
    <li><a href="#" (click)="showSelectedImage(1)">Option 1</a></li>
    <li><a href="#" (click)="showSelectedImage(2)">Option 2</a></li>
    <li><a href="#" (click)="showSelectedImage(3)">Option 3</a></li>
</ul>

and I have 3 images:

<img class="hidden" src="image1.png" alt />
<img class="hidden" src="image2.png" alt />
<img class="hidden" src="image3.png" alt />

In app.component.ts I have this method:

showSelectedImage(image) {
    // ... 
}

我需要做的是从下拉菜单中选择图像时,我需要显示该图像,并隐藏其他图像。

3 个答案:

答案 0 :(得分:3)

只需使用相应的源生成一个图像:

<ul class="dropdown-menu">
    <li *ngFor="let i of [1,2,3,4,5,6]">
        <a href="#" (click)="showSelectedImage(i)">Option {{i}}</a>
    </li>
</ul>

<img src="image{{imageId}}.png" *ngIf="imageId" />

组件:

imageId:Number;

showSelectedImage(id){
    this.imageId = id
}

答案 1 :(得分:1)

如果要分隔图像网址和说明,可以将它们放在组件代码中的列表中,然后使用ngFor将它们显示在模板中。这样他们就可以被称为任何东西(而不是必须是image1,image2,image3等),并且可以在将来轻松更改,而无需每次都编辑模板(例如,从动态列表中)。

例如为: 模板:

<ul class="dropdown-menu">
    <li *ngFor='let image of images'><a href="#" (click)="showSelectedImage(image)">{{image.description}}</a></li>
</ul>

<img *ngIf='selectedImage' src="{{selectedImage.src}}" alt />

app.component.ts:

selectedImage;
images: list = [
    {src: 'image1.jpg', description: 'Image 1'},
    {src: 'image2.jpg', description: 'Image 2'},
    {src: 'someotherimage.jpg', description: 'Some other Image'}
];

showSelectedImage(image) {
    this.selectedImage = image;
}

Example Plunker

答案 2 :(得分:0)

<ul class="dropdown-menu">
    <li><a href="#" (click)="showSelectedImage(1)">Option 1</a></li>
    <li><a href="#" (click)="showSelectedImage(2)">Option 2</a></li>
    <li><a href="#" (click)="showSelectedImage(3)">Option 3</a></li>
</ul>


<img class="hidden" src="image1.png" alt *ngIf="selectedImage==1"/>
<img class="hidden" src="image2.png" alt *ngIf="selectedImage==2"/>
<img class="hidden" src="image3.png" alt *ngIf="selectedImage==3"/>

app.component.ts

private selectedImage: number;

showSelectedImage(imageNumber: number) {
    this.selectedImage = imageNumber; }