2017-09-29 83 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

相关问题