2017-09-29 95 views

回答

1

指令可以是你的問題的解決方案。

的src /應用/ width.directive.ts

import { Directive, ElementRef, Input } from '@angular/core'; 

@Directive({ selector: '[width]' }) 
export class widthDirective { 

    @Input() 
    set width(width: number) { 
     this.el.nativeElement.style.width = `${this._width}px`; 
    } 

    constructor(el: ElementRef) {} 
} 

然後在任何組件,您可以使用:

<div class="page home-page" width [width]="500"> 

如果你想使你的指令,任何地方訪問你可以按照this answer

+0

我該如何做到這一點。 calc(100% - 200px)? – Joseph

+0

您可以將您的'calc'功能'WidthDirective'內,這樣做'@input() 集(寬度:數){ this.el.nativeElement.style.width = \'$ {this.calc (100% - 寬度)} px \'; '它取決於'calc()'返回值,你能告訴我函數嗎? – Lilrom

1

在角2/4所有樣式(除全球主要的樣式表)封裝,所以當你包括像這樣的樣式表:

@Component({ 
    selector: 'component-name', 
    templateUrl: './component.html', 
    styleUrls: ['./component.css'] 
}) 

component.css所有樣式將只適用於component.html(如果你不使用像/deep/和相同的東西)。所以隨意更改當前佈局的寬度,不會影響其他佈局!

+0

但是我的div class =「page home-page」是在其他組件上找到的。你怎麼能在登錄組件上調用div class =「page home-page」並將它的寬度設置爲你想要的? – Joseph

+0

@Joseph,如果它在另一個組件中,你不能從當前的'component.css'文件訪問它。您可以在'styles.css'文件中編寫全局樣式(它位於項目的根目錄附近)。 –

+0

@商業自殺。是的,我在styles.css中應用了div class =「page home-page」設計,並且只想在login.component上更改其寬度。只在login.component上,而不在其他組件 – Joseph