Ngif with images Angular2

时间:2017-07-12 08:19:03

标签: angular typescript angular-ng-if

I have 5 'pages' like

http://localhost:4201/app?part=1
http://localhost:4201/app?part=2
http://localhost:4201/app?part=3
....

And I have 5 images, and I would like to match each image to each page with help of ngIf (if it is possible).

For this purpose in my Component I have this line, which tells me which part do I have now

  ngOnInit() {
    this.pageNumber = this.activatedRoute.snapshot.queryParams["part"];
}

Also I have in my Component

myImg = '../../assets/image1.jpg'; 

And in template I have

<img [src]="myImg"/>

What I want to have is like logic like

if pageNumber = 1 then <img [src]="myImg1"/>
if pageNumber = 2 then <img [src]="myImg2"/>
if pageNumber = 3 then <img [src]="myImg3"/>

and so on...

Could you please tell me how could I write ngIf statement in my case? I tried examples from documentation, but none of them worked for me .

2 个答案:

答案 0 :(得分:2)

你不需要病情。相反,只放一张图片,并像这样设置其来源

<img [src]="myPathToImage + imageNumber + imageExt" />

在您的控制器中

myPathToImage = "../../assets/image";
imageNumber = this.activatedRoute.snapshot.queryParams["part"];
imageExt = ".jpg";

顺便说一句,如果你使用的是角度CLI并没有触及文件夹结构,我认为你的路径是assets/...而不是../../assets/...

答案 1 :(得分:2)

操作Component类中的数据而不是模板上的数据

是一种很好的做法

在您的组件的课程中,您可以这样做:

SELECT table1."id", table1.val, table2.val,
CASE WHEN table2.val IS NOT null AND table2.val != 'N' THEN table2.val
    WHEN table2.val = 'N' THEN null 
    WHEN table1.val = 'N' THEN null
ELSE table1.val
END AS results
FROM table1
LEFT JOIN table2 ON table2."id" = table1."id"

+----+-----+--------+---------+
| id | val |  val   | results |
+----+-----+--------+---------+
|  1 | A   | N      | [null]  |
|  2 | A   | B      | B       |
|  3 | N   | [null] | [null]  |
|  5 | A   | [null] | A       |
|  8 | A   | B      | B       |
|  9 | N   | B      | B       |
| 10 | N   | N      | [null]  |
+----+-----+--------+---------+

+----+---------+
| id | results |
+----+---------+
|  1 | [null]  |
|  2 | B       |
|  3 | [null]  |
|  5 | A       |
|  8 | B       |
|  9 | B       |
| 10 | [null]  |
+----+---------+

然后在你的模板上:

ngOnInit(){
    let pageNumber = this.pageNumber = this.activatedRoute.snapshot.queryParams["part"];
    this.imageToBeDisplayedOnTemplate = `myImg${pageNumber}.jpg`
}