【问题标题】:Angular 5 binding attribute from @Input来自@Input 的 Angular 5 绑定属性
【发布时间】:2018-11-29 18:29:10
【问题描述】:

(已编辑)我有一个简单的 jarallax,只有一个 div 和组件中的对应配置:

<div class="view cover-jarallax" data-jarallax="{"speed": '0.w'}" 
style="background-image: url(imgurl);' +
'height: ' + this.height + ';"></div>

我需要再使用一两次,所以我试图让它动态化,从父组件接收速度、url 和高度作为@Input。

问题是我在这样做时遇到了一些问题,因为直接使用动态绑定到 div 的属性。我的意思是:

<div class="view cover-jarallax" [data-speed]="datajarallax" 
[ngStyle]="style"></div>

在组件中:

import {Component, Input, OnInit} from '@angular/core';

@Component({
selector: 'app-middle-parallax',
templateUrl: './middle-parallax.component.html',
styleUrls: ['./middle-parallax.component.scss']
})
export class MiddleParallaxComponent implements OnInit {

@Input() speed: number;
@Input() imgURL: string; // time to wait after finish typing to start 
deleting the current string
@Input() height: string;
style = '';
datajarallax = '';

constructor() { }

ngOnInit() {

this.style = 'background-image: url(\'' + this.imgURL + '\');' +
  'height: ' + this.height + '; ' +
  'background-repeat: no-repeat; ' +
  'background-size: cover; ' +
  'background-position: center center;';
this.datajarallax = '{"speed": ' + this.speed + '}';
}

}

那行不通,我想那是因为我刚才说的,但它并没有找到我要走的路。有什么帮助吗?

编辑:控制台显示此错误:

ERROR Error: Cannot find a differ supporting object 'background-image: 
url('https://images.unsplash.com/photo-1484417894907-623942c8ee29?ixlib=
rb-0.3.5&s=db802b72adc82f97904d37dde9d0d401&dpr=1&auto=format&fit=crop&w=1000&q
=80&cs=tinysrgb');height: 400px; background-repeat: no-repeat; 
background-size: cover; background-position: center center;'

解决方案(样式):

我必须将样式字符串作为对象传递给 ngStyle:

this.style = {'background-image': 'url(\'' + this.imgURL + '\')' ,
'height': this.height,
'background-repeat': 'no-repeat',
'background-size': 'cover',
'background-position': 'center center'};

EDIT2:现在样式是绑定的,但 data-jarallax 没有,既不是作为对象也不是作为字符串

<div class="view cover-jarallax" [data-jarallax]="datajarallax" 
[ngStyle]="style"></div>

.

this.datajarallax = {'speed': 0.2};
this.datajarallax = '{\'speed\': 0.2}';

【问题讨论】:

  • 尝试data-jarallax="{{datajarallax}}"并将datajarallax设置为{"speed": this.height}

标签: angular data-binding binding


【解决方案1】:

差不多了。你只是想念""。也可以使用ngStyle

<div class="view cover-jarallax" data-jarallax="{{datajarallax}}" [ngStyle]= 
"style"></div>

datajarallax 应该是一个对象

datajarallax = {"speed": ' + this.height + '};

【讨论】:

  • 对不起伙计,这没用,我想我以前也试过。
  • ERROR 错误:找不到不同的支持对象 'background-image: url('undefined');height: undefined;背景重复:不重复;背景尺寸:封面; background-position: center center;'
  • PS:我只是在 OnInit 中放了一个绑定的控制台日志,它就起作用了
  • 当然。您需要将其放在 oninit 中,因为您正在访问输入值。因为oninit是一个生命周期钩子所以它一直等到输入值绑定
  • 我刚刚用更多数据编辑了问题,我仍然没有找到问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-29
  • 2018-09-29
  • 2018-09-11
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 2020-11-30
相关资源
最近更新 更多