[英]Ngif with images Angular2
I have 5 'pages' like 我有5个“页面”,例如
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). 我有5张图片,我想在
ngIf
帮助下(如果可能)将每张图片与每个页面匹配。
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? 您能告诉我如何编写ngIf语句吗? I tried examples from documentation, but none of them worked for me .
我尝试了文档中的示例,但没有一个对我有用。
You don't need a condition. 您不需要条件。 Instead, put only one picture, and set its source like this
相反,只放置一张图片,并像这样设置其来源
<img [src]="myPathToImage + imageNumber + imageExt" />
In your controller 在您的控制器中
myPathToImage = "../../assets/image";
imageNumber = this.activatedRoute.snapshot.queryParams["part"];
imageExt = ".jpg";
By the way, if you are using angular CLI and didn't touche the folder structure, I think that your path is assets/...
and not ../../assets/...
顺便说一句,如果您使用的是角度CLI且未涉及文件夹结构,我认为您的路径是
assets/...
而不是../../assets/...
It's good practice to manipulate data inside the Component class and not on the Template 优良作法是在Component类而不是Template中处理数据
In your component's class you could do: 在组件的类中,您可以执行以下操作:
ngOnInit(){
let pageNumber = this.pageNumber = this.activatedRoute.snapshot.queryParams["part"];
this.imageToBeDisplayedOnTemplate = `myImg${pageNumber}.jpg`
}
Then on your template: 然后在您的模板上:
<img [src]="imageToBeDisplayedOnTemplate"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.