【问题标题】:Why we use - ngAfterContentInit lifecycle method为什么我们使用 - ngAfterContentInit 生命周期方法
【发布时间】:2021-05-15 00:08:43
【问题描述】:

我正在学习 Angular。有很多生命周期方法。例如 ngOnChanges 每次在子组件的输入属性中出现新值时运行 - 这些值是按值传递的。

我不明白这个方法 - ngAfterContentInit。在角度文档中说:

https://angular.io/guide/lifecycle-hooks

在 Angular 将外部内容投射到组件的视图或指令所在的视图后响应。

但这似乎不是很好的解释。有人可以告诉我为什么我们使用并更好地理解一个真实世界场景 - 用例

【问题讨论】:

    标签: angular angular-lifecycle-hooks


    【解决方案1】:

    有可能以角度进行内容投影

    // my-container-component.template
    <header>
     this is my container
    </header>
    <main>
       <span> it contains something passed from outside </span>
       <ng-content></ng-content>
    </main>
    

    用法:

     <my-container><span>something that will be rendered be INSIDE of the component</span></my-container>
    

    span 将代替组件内的ng-content 元素呈现。 这段通过的html通常被称为角度的“内容”。所以ngAfterContentInit() 是与此内容交互的好钩子,如果你需要的话

    【讨论】:

    • 感谢安德烈的回答。我接受了你的回答
    • 顺便说一句 - 插入我的内容后 - 我如何访问 ngAfterContentInit 中的内容?
    • 有一个@ContentChild@ContentChildren 查询,在ts中获取你的元素
    猜你喜欢
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    相关资源
    最近更新 更多