【发布时间】: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