Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

html - Set component style from variable in Angular 2

My goal is to set a style (height and width in this case) from a component variable using the "styles" attribute. I would think there is a simple data binding method but that may be wishful thinking...

For example if I were using the html mustache binding it might look like this:

@Component({
    selector: '[sidebar]',
    templateUrl: 'app/Nav/sidebar.comp.html',
    styles: [`
        .sidebar-nav {
            overflow: scroll;
            height: {{ height }};
        }
        .sidebar {
            height: {{ 0.9 * height }};
            width: {{ 0.21 * width }};
        }
    `]
})

export class SidebarComp {
    width: number;
    height: number;

    constructor() {
        this.height = window.innerHeight;
        this.width = window.innerWidth;
    }
}

Obviously this is all wrong but I've tried some more likely permutations and had no luck finding solutions on the Angular site, Stack Overflow, or Google. I may be reduced to using ngStyle inline but that's not ideal in this case.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can style the host element like

@Component({
  selector: '[sidebar]',
  templateUrl: 'app/Nav/sidebar.comp.html',
  host: {
    '[style.height.px]':'0.9 * height',
    '[style.width.px]':'0.21 * width'
  }

})

export class SidebarComp {
    width: number;
    height: number;

    constructor() {
        this.height = window.innerHeight;
        this.width = window.innerWidth;
    }
}

and the content (app/Nav/sidebar.comp.html) like

<div class="sidebar-nav" [style.overflow]="'scroll'" [style.height.px]="height">

or

<div class="sidebar-nav" [ngStyle]="{overflow: 'scroll', height: height + 'px'}">

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...