@Input

时间:2018-06-20 15:02:24

标签: angular data-binding binding

(已编辑)我有一个简单的jarallax,其中只有一个div,并且在组件中具有相应的配置:

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

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

问题是由于使用直接绑定到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}';

1 个答案:

答案 0 :(得分:1)

快到了。您只是想念""。也使用ngStyle

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

datajarallax应该是一个对象

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