如何将 CSS 类应用于 AngularDart 中的另一个组件?

Ser*_*rov 8 typescript ecmascript-6 angular-dart angular

假设有一个简单的框架来显示弹出窗口:

@Component(
  selector: 'popup-host',
  template: '''
      <div class="popup-container">
        <ng-template #popupRef></ng-template>
      </div>
  ''',
  styles: ['.popup-container { position: absolute; top: 100; left: 100; z-index: 100; }'],
)
class PopupContainerComponent {
  final PopupController _controller;
  final ComponentLoader _loader;

  PopupContainerComponent(this._controller, this._loader);

  void ngOnInit() {
    _controller.container = this;
  }

  @ViewChild('popupRef', read: ComponentRef)
  ComponentRef popupRef;

  void render(PopupConfig config) {
    final componentRef = _loader.loadNextTo(config.factory, popupRef);
    if (componentRef.instance is HasValueSetter) {
      componentRef.instance.value = config.value;
    }
  }
}

@Injectable()
class PopupController {
  PopupContainerComponent _container;
  set container(PopupContainerComponent container) => _container = container;

  void showPopup(PopupConfig config) {
    container.render(config);
  }
  ...
}

class PopupConfig {
  final ComponentFactory factory;
  final dynamic value;
  PopupConfig(this.factory, [this.value]);
}

abstract class HasValueSetter {
  set value(dynamic value);
}
Run Code Online (Sandbox Code Playgroud)

然后可以这样使用:

// Somewhere in the root template
<popup-host></popup-host>

// In popup.dart
@Component(
  selector: 'happy-popup',
  template: '''
      <div class="header">This is the popup content.</div>
      <div class="main">The value is {{value}}.</div>
      <div class="footer">I am happy!</div>
  ''',
)
class HappyPopupComponent implements HasValueSetter {
  @override
  dynamic value;
}

// In some_other.dart
@Component(
  ...
  styles: [
    '.header { font-weight: bold }',
    '.main { color: red }',
    '.footer { color: green; font-style: italic }',
  ],
  ...
)
class SomeOtherComponent {
  final PopupController _popupController;
  ...
  SomeOtherComponent(this._popupController, ...) ...;

  void displayPopup() {
    _popupController.showPopup(HappyPopupComponentNgFactory, 42);
  }
}
...
Run Code Online (Sandbox Code Playgroud)

有没有办法将样式从 to 转发<some-other-component><happy-popup>而不必在应用程序的根目录中定义它们?

Din*_*ino 6

您可以通过将组件代码拆分为单独的文件来实现这一点 - 或者在您的情况下使用单独的 CSS 文件。

styles您可以使用 .css 文件导入 CSS 文件,而不是直接在组件的 - 中编写样式styleUrls。这样您就可以传递带有样式的文件,并且该文件可以在多个组件之间共享。

@Component(
      styleUrls: ['./hero1.css', './folder/hero2.css'],
)
Run Code Online (Sandbox Code Playgroud)

请记住,styleUrls 中的 URL 是相对于组件的。

导入 css with 的另一个好处styleUrls是它还授予您在该文件中使用导入的能力。

英雄1.css

@import './folder/hero2.css';
Run Code Online (Sandbox Code Playgroud)

仅供参考:将组件代码拆分为单独的文件是一种常见做法。

  • 英雄飞镖
  • 英雄.css
  • 英雄.html

然后在您的 dart 文件中将它们引用为:

@Component(
      templateUrl: './hero.html',
      styleUrls: ['./hero.css'],
)
Run Code Online (Sandbox Code Playgroud)

有关这方面的简要信息,请参阅AngularDart - 组件样式