【问题标题】:Use @ViewChildren/@ContentChildren in combination with router-outlet将@ViewChildren/@ContentChildren 与路由器插座结合使用
【发布时间】:2019-07-09 14:53:31
【问题描述】:

我正在尝试构建这个:

┌--------------------------------------------┐
| -Page 1-   -Page 2-   -Page 3-             |
├----------┬---------------------------------┤
| Link 1   | <router-outlet></router-outlet> |
| Link 2   |                                 |
| Link 3   |                                 |
|          |                                 |
|          |                                 |

左侧的链接列表取决于页面。

典型的页面如下所示:

<div>
  <app-component-1 appAnchor anchorTitle="Link 1"></app-component-1>
  <app-component-2 appAnchor anchorTitle="Link 2"></app-component-2>
  <app-component-3 appAnchor anchorTitle="Link 3"></app-component-3>
</div>

有一些指令 appAnchor 关联到 @Input() anchorTitle: string 。我想自动捕获它们并更新左侧菜单。

当我尝试通过router-outlet 查询这些元素时,问题就来了。

所以我尝试了:

@ViewChildren(AnchorDirective)
viewChildren: QueryList<AnchorDirective>;

@ContentChildren(AnchorDirective)
contentChildren: QueryList<AnchorDirective>;

ngAfterContentInit(): void {
  console.log(`AppComponent[l.81] contentChildren`, this.contentChildren);
}

ngAfterViewInit(): void {
  console.log(`AppComponent[l.85] viewChildren`, this.viewChildren);
}

但我总是得到一些空的QueryList:

QueryList {dirty: false, _results: Array(0), changes: EventEmitter, length: 0, last: undefined, ...}

我也试过了:

@ContentChildren(AnchorDirective, {descendants: true})
@ContentChildren(AnchorDirective, {descendants: false})

最后,我尝试在最后一刻查询元素:

<router-outlet (activate)="foo()"></router-outlet>

注意:我不希望子组件通过服务向父组件发送数据,因为它会导致一些ExpressionChangedAfterItHasBeenCheckedError 和is considered as a bad practice。我真的更喜欢直接从父组件查询链接。

编辑:这是一个stackBlitz 显示问题。如果在组件内部使用@ViewChildren,一切正常。但如果在根组件中使用@ViewChildren,则会失败。

【问题讨论】:

  • “当我尝试通过路由器插座查询这些元素时”,这是什么意思?如果您在示例中添加了一些类名,那么在答案/cmets 中会更容易引用
  • @Drenai 我正在尝试引用具有 AnchorDirective 的元素(因此具有 appAnchor 属性的元素)。我在问题末尾添加了一个有效的 StackBlitz。
  • 只是想知道这一切的最终目标是什么?尝试达到什么目标?因为这一切看起来有点……奇怪而且太复杂了。
  • 伟大的 StackBlitz 演示。很好的解释问题????
  • @Dimanoid 目的是做一个自动目录。

标签: angular typescript


【解决方案1】:

关于ContentChildren 工作原理的讨论正在进行中,here 与您的问题密切相关。

在this comment 中解释说:

在 Angular 内容投影和查询中,它的意思是“内容原样 写在模板中”而不是“在 DOM 中可见的内容”

和

这种心智模型的结果是 Angular 只关注 模板中的子节点(而不是模板中的子节点) 渲染的 DOM)。

与上述问题类似,通过router-outlet 激活的组件不会被视为ViewChildren 或ContentChildren。它们只是 DOM 子级,这并不意味着在视图和内容查询方面有任何角度。没有办法(截至今天)用ViewChild或ViewChildren或ContentChild或ContentChildren查询它们

我建议解决您的问题是使用activate 事件和RouterOutlet 的component 属性的组合来实现所需的行为。因此:

如下定义router-outlet:

<router-outlet #myRouterOutlet="outlet" (activate)='onActivate()'></router-outlet>

并按如下方式使用:

@ViewChild("myRouterOutlet", { static: true }) routerOutlet: RouterOutlet;
nbViewChildren: number;
links = [];

onActivate(): void {
  setTimeout(() => {
    const ancList: QueryList<AnchorDirective> = (this.routerOutlet.component as any).children;

    this.nbViewChildren = ancList.length;
    this.links = ancList.map(anc => anc.anchorTitle);
  })
}

这是一个改进了打字的工作演示:https://stackblitz.com/edit/angular-lopyp1

另请注意,setTimeout 是必需的,因为在组件生命周期尚未开始或完成的路由期间会触发 onActivate。 setTimeout 确保组件生命周期已完成,并且组件和底层查询也已准备就绪。

【讨论】:

  • 这很聪明,但应用程序组件现在将非常紧密地耦合到路由器出口组件。我想不出有人会使用这种方法(包括 setTimeout)而不是服务在组件之间传递信息的任何理由——尤其是从子级到父级
  • 我同意紧耦合。但是 settimeout 是无害的,它是处理此类情况的首选方式。从专业的角度来看,我也更喜欢使用服务在不相关的组件之间传递数据。我提供了这个解决方案,因为在问题中明确指出他不想使用服务。
  • Fair enouth? 我在查看 StackBlitz 演示时学到的一件事 - 如果使用 (activate)="handleActivate($event)",$event 是对在插座中显示的组件的引用。这很方便
  • @Drenai 我一直专门使用这种方法将 ARIA 标签和某些 css 类添加到我的路由器出口组件中——我特别不希望该组件知道它。例如role='main' 可能会添加到组件 X,但前提是它是顶级组件。像这样的东西。在 Ivy 颠倒新插入元素的顺序之前工作得很好!
【解决方案2】:

(activate)="handleActivate($event)" 选项不起作用,因为 router-outlet 元素尚未初始化。在这种情况下,$event 确实是组件实例,但在这里并没有真正的帮助

ViewChildren、ContentChildren 似乎不适用于router-outlet。我不认为他们会,但用你的 StackBlitz 演示对其进行了很好的测试

您必须使用服务,这是执行此操作的标准方式,也是迄今为止最灵活的方式。您将能够使用 ChangeDetectorRef.detectChanges() 绕过 ExpressionChangedAfterItHasBeenCheckedError,或者更好的是,使用 BehaviorSubject 和 next 中的值。在您的模板中使用async 管道订阅,您不会收到这些错误

【讨论】:

    猜你喜欢
    • 2020-01-13
    • 2021-03-13
    • 2017-02-15
    • 2017-04-29
    • 2018-07-28
    • 2019-01-05
    • 2017-02-13
    • 2016-12-30
    • 1970-01-01
    相关资源
    最近更新 更多