AngularDart - 将静态定义的子组件与动态聚合一次的方法

AngularDart - Way to aggregate statically defined child component with dynamic once

我想将静态定义的子组件与可能来自流的动态一次聚合在一起。我想要一种通用的方法来在此轮播中定义轮播,我可以在其中拥有类型化的组件集合。集合可以静态或动态定义。下面是一个例子:

import 'package:angular/angular.dart';
import 'package:angular/core.dart';
import 'package:angular_components/angular_components.dart';


/**
 *
 */
@Component(
    selector: 'md-text',
    styleUrls: const ['md_text.css'],
    template: '<li>{{name}}</li>',
    directives: const [
      materialDirectives,
    ]
)
class TextComponent implements OnInit{
  @Input()
  String name;

  TextComponent([this.name]);

  TextComponent.withName(String name)
      : this(name);

  @override
  ngOnInit() {
  }
}

@Component(
    selector: 'md-texts',
    styleUrls: const ['text_component.css'],
    template: '<ol><md-text *ngFor="let component of components" [name]="component.name"></md-text><ng-content></ng-content></ol>',
    directives: const [
      CORE_DIRECTIVES,
      materialDirectives,
      TextComponent
    ]
)
class TextsComponent<TextComponent> implements OnInit
{
  Set<T> _components;

  Set<T> get components => _components;

  addComponent(T component){
    this._components.add(component);
  }

  removeComponent(T component) {
    this._components.remove(component);
  }

  TextsComponent() {
    this._components = new LinkedHashSet<T>();
    TextComponent declarativeChannel = new TextComponent.withName("United States");
    this.addComponent(declarativeChannel);
  }

  @override
  ngOnInit(){
    print("I am here");
  }
}

在我的仪表板组件中,我静态定义了如下用法:

<md-texts>
    <md-text [name]="'Liberty'"></md-text>
    <md-text [name]="'Life'"></md-text> 
<md-texts>

显示如下 美国 自由 生活

我想要做的是将 "Liberty" 和 "Life" 也聚合到我的组件集合中,这样我就可以使用下一个和上一个按钮来控制它。我也只想在需要索引时呈现它们。在 AngularDart 中执行此操作的最佳方法是什么。

我在旧版本中发现了类似的问题,但在旧版本中 How to reference child component from its parent in AngularDart in AD 1.0.0 and How to reference child component from its parent in AngularDart in AD 1.0.0

此致,希望我已经解释了我的问题,并且我将清楚地了解解决此设计问题的正确方法。

您可以使用 @ViewChildren@ContentChildren 来查询子组件。 @ViewChildren 将查询模板中声明的组件,而 @ContentChildren 将查询投影到模板中 <ng-content> 的组件。

值得一提的是,在您的示例中,您的动态 TextComponent 被创建了两次。首先,在构造函数中创建一个,然后在模板中声明 <md-text> 时再次创建。这意味着您保留引用的实例实际上并不是在您的视图中呈现的组件。为避免这种情况,不要费心去创建实例。只需保留创建它们所需的数据模型,然后将其通过声明组件的模板中的输入传递。然后,您可以使用 @ViewChildren 查询您创建的那些组件。

这是一个例子

@Component(
  selector: 'md-texts',
  template: '''
    <ol>
      <md-text *ngFor="let text of texts" [text]="text"></md-text>
      <ng-content></ng-content>
    </ol>
  ''',
  directives: const [NgFor, TextComponent],
)
class TextsComponent {
  /// Text that was projected through `<ng-content>`.
  @ContentChildren(TextComponent)
  QueryList<TextComponent> contentTexts;

  /// Text that was created in our view from our model.
  @ViewChildren(TextComponent)
  QueryList<TextComponent> viewTexts;

  /// Data model for the text in our view.
  final List<String> texts = [
    ...
  ];
}

或者,您可以从视图中的单一数据源呈现所有 <md-text>,并依靠传入静态数据模型而不是投影组件。