在Angular 1.5中,引入了.component(),似乎被认为是一种好习惯。我目前正在迁移到ui-router 1.0,它允许(并建议)路由到组件。 所以我重构了一个控制器/模板路由到一个组件路由器工作得很好:组件"示例"被注入到自己的DOM节点中的ui-view容器中:
然而,这会破坏我的布局(使用角度材质)。我使用的解决方法是简单地复制和使用css类角度材料用于插入节点上的布局。但是,我认为这是一个" hacky"解决方案:如果角度材料改变它的布局模块怎么办?
更好的解决方案是将布局属性甚至css类添加到"示例"元件。但我怎么能这样做?这甚至可能吗?
我认为这个问题与以下内容有关,我提供了针对特定问题的解决方法。但我对更通用的解决方案感兴趣:Using angular component breaks material layout
答案 0 :(得分:3)
我在Angular 1.5项目中遇到了同样的问题,我也使用了angular-ui-router和Angular Material组件。一种可能的解决方案是使用string-based binding将两个属性绑定到组件中:布局和 flex 。您可以通过以下方式指定ui-routing状态,为这两个绑定属性(通常为“行”和“ 100 ”)提供值:
var exampleState = {
name: 'examplestate',
url: '/', // change this to your desired path
component: 'example',
resolve: {
layout: function () {
return 'row'; // you can change this value depending on your UI requirements
},
flex: function () {
return '100'; // you can change this value depending on your UI requirements
}
}
};
在模块的config方法中,您以标准方式定义exampleState:
$stateProvider.state(exampleState);
最后,在组件定义中,在定义绑定时,将这两个属性添加到绑定属性列表中。 打字稿中的示例:
export class ExampleComponent implements ng.IComponentOptions {
public bindings: any;
public controller: any;
public template: string;
constructor() {
this.bindings = {
layout: '@',
flex: '@'
};
this.controller = ExampleComponentController;
this.template = ExampleViewTemplate;
}
}
您可以通常的方式将此组件添加到角度模块中:
.component('example', new ExampleComponent());
这将导致DOM中的以下HTML元素(由angular-ui-router自动创建):
<example layout="row" flex="100" class="ng-scope ng-isolate-scope layout-row flex-100">
因此,您无需在代码中插入任何手动CSS样式。您正在使用component-element上的标准Angular Material属性。