angular7:无法显示img

angular 7: Cannot display the img

我正在做这样的事情 angular js 示例: https://jsbin.com/gumaraz/edit?html,output

但我需要处理 Angular 7 我尝试将代码从 Angular.js 升级到 angular 但是它无法显示任何内容

component.html

  WidthLength : <input type="number" min="1" step="5" [(ngModel)]="widthLength" (change)="showPic()" ><br>
  HeightLength : <input type="number" min="1" step="5" [(ngModel)]="heightLength" (change)="showPic()"><br>

  <img [src]='imageUrl '/>

component.ts

  widthLength = '1024';
  heightLength = '768';
  imageUrl = 'https://lorempixel.com/{{widthLength}}/{{heightLength}}/';

  showPic() {
    if (this.widthLength !== null && this.heightLength !== null &&
      this.widthLength !== undefined && this.heightLength !== undefined) {
      this.imageUrl = 'http://lorempixel.com/' + this.widthLength + '/' + this.heightLength + '/';
    } else {
      alert('null');
    }
  }

我的代码(stakblitz): https://stackblitz.com/edit/angular-555ojr

谁能帮帮我

试试这个(通过安全网络 https

imageUrl = 'https://lorempixel.com/400/400/';
<img [src]=" imageUrl ">

如果要动态设置高度和宽度,请尝试使用变量设置。

Working Example

您的 URL 格式不正确。您正在尝试获取类似

的资源

https://lorempixel.com/{{widthLength}}/{{heightLengt} 这显然不存在。正确准备您的 URL,因为您的 widthLengthheightLength 没有得到解决。

我只能假设那些是 component/local 变量所以它应该更像

imageUrl = http://lorempixel.com/${widthLength}/${heightLength}/; 在局部变量的情况下,或 this.widthLength 等在组件字段的情况下

由于您使用实际代码编辑了问题:

  1. 删除虚拟初始化值
  2. 在某处打电话给showPic()
  3. 使用 HTTPS

      widthLength = '1024';
      heightLength = '768';
      imageUrl = null; // removed dumb initialization value.
    
      ngOnInit(){
         this.showPic(); // call it here for example
      }
      showPic() {
        if (this.widthLength !== null && this.heightLength !== null &&
          this.widthLength !== undefined && this.heightLength !== undefined) {
          this.imageUrl = 'https://lorempixel.com/' + this.widthLength + '/' + this.heightLength + '/';
        } else {
          alert('null');
        }  
       }
    

如果您仍然遇到问题,请准备工作 stackblitz 并共享编辑器 link。