zoukankan      html  css  js  c++  java
  • [Angular] Communicate Between Components Using Angular Dependency Injection

    Allow more than one child component of the same type. Allow child components to be placed within the views of other custom components.

    In previous post, we have seen how to use @ContentChild to asscomplish compound component implementation.

    It has some limitations, for example, 

    <toggle (toggle)="onToggle($event)">
      <toggle-on>On</toggle-on>
      <toggle-off>Off</toggle-off>
       <!-- Does not work when has multi children components -->
      <toggle-on>On</toggle-on>
      <toggle-off>Off</toggle-off>
    
      <!-- Does not work when there are some nested component -->
      <other-component></other-component>
      <toggle-button></toggle-button>
    </toggle>

    The reason for that is @ContentChild is only looking for the first matched child component, so that the only first child component get updated. Of course, we can use @ContentChildren with QueryList to solve the problem for multi child components, but @ContentChildren doesn't help with nested component.

    So the solution is using Angular dependency injection, we want to inject 'ToggleComponent' into its child component. So that from the Child component, we can reference toggle component' state. For example:

    toggle.on.component.ts:

    import { Component } from '@angular/core';
    
    import { ToggleComponent } from './toggle.component';
    
    @Component({
      selector: 'toggle-on',
      template: '<ng-content *ngIf="toggle.on"></ng-content>',
    })
    export class ToggleOnComponent {
      constructor(public toggle: ToggleComponent) { }
    }

    We inject 'ToggleComponent' and inside the template, we reference toggle.on state form ToggleComponent.

  • 相关阅读:
    c++经典书籍介绍
    jpeg软解码实现介绍
    视频编解码类型调查——抖音客户端
    微机接口复习
    更改MySQL数据库的密码
    python学习之创建我的第一个Django项目
    关于 V831 linux 调用 gpio 的一些通用操作。
    SpringBoot整合H2内存数据库快速启动测试
    MybatisPlus的各种功能使用笔记综合!
    MybatisPlus的自动填充功能使用!
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9764146.html
Copyright © 2011-2022 走看看