我想要实现的目标:
<ion-header [style.background-color]="(style|async)?.logoBackground">
<ion-navbar >
<button ion-button icon-only menuToggle [style.background-color]="(style|async)?.menuButtonBackground">
<ion-icon name="menu"></ion-icon>
</button>
<ion-title [style.background-color]="(style|async)?.logoBackground">
<dynamic-logo [style]="style"></dynamic-logo>
</ion-title>
</ion-navbar>
</ion-header>
我必须一遍又一遍地重复使用这段代码。
“style”是 JSON 对象的变量,我动态获取其中包含“应用程序的样式表”。
我很愿意在其他页面上写得这么简单:
<dynamic-header [style]="style"></dynamic-header>
并有一个组件来设置这些(组件附加在下面)。
虽然这在 ionic2 中是不可能的,因为它会包裹 <ion-header>
在 <dynamic-header>
因此无法正确渲染页面。
所以我想知道是否有一种替代方法可以将其作为组件,也许是一种将其作为指令的方法,我只是无法找到有关 @Directive 的必要信息..
还尝试了带有绑定(bind)的@Directive <ion-content dynamic-content [style]="style">...</>
以及
[style]="(style|async)"
给出WARNING: sanitizing unsafe style value [object Object] (see http://g.co/ng/security#xss).
TS:
import { Attribute, ChangeDetectionStrategy, Component, ElementRef, Input, Renderer, ViewEncapsulation } from '@angular/core';
import { PageStyle } from "../../providers/company-service";
@Component({
selector: 'dynamic-header',
templateUrl: 'dynamic-header.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
})
export class DynamicHeaderComponent {
@Input() style: PageStyle;
}
HTML:
<ion-header [style.background-color]="(style|async)?.logoBackground">
<ion-navbar >
<button ion-button icon-only menuToggle [style.background-color]="(style|async)?.menuButtonBackground">
<ion-icon name="menu"></ion-icon>
</button>
<ion-title [style.background-color]="(style|async)?.logoBackground">
<dynamic-logo [style]="style"></dynamic-logo>
</ion-title>
</ion-navbar>
</ion-header>
改革为指令
import { Directive, HostBinding, Attribute, ChangeDetectionStrategy, Component, ElementRef, Input, Renderer, ViewEncapsulation } from '@angular/core';
import { PageStyle } from "../../providers/company-service";
@Directive({
selector: 'dynamic-content',
/* templateUrl: 'dynamic-content.html',
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
*/
})
export class DynamicContentComponent {
@Input() style: PageStyle;
@HostBinding('style.background-image')
get getBackgroundImage() {
if (this.style) {
return this.style.backgroundImage;
}
}
@HostBinding('style.background-repeat')
get getBackgroundRepeat() {
if (this.style) {
return "no-repeat";
}
}
@HostBinding('style.background-size')
get getBackgroundSize() {
if (this.style) {
return "cover";
}
}
@HostBinding('style.color')
get getTextColor() {
if (this.style) {
return this.style.textColor;
}
}
}
最佳答案
在指令中,您只能绑定(bind)单一样式
export class DynamicHeaderComponent {
@Input() style: PageStyle;
// repeat this getter for every style property
@HostBinding('style.background-color')
get backgroundColor() {
if(this.style) {
return this.style.backgroundColor;
}
}
}
关于html - 动态设置ionic2组件的Style属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42020645/