angular父子组件通信

63 阅读1分钟
  • 1,属性绑定:以属性的方式传递给子组件,可以是方法/属性

    <--父组件-->
    // .html
    <app-child [inputProperty]="parentMethod"></app-child>
    // components.ts
    export class ParentComponent {
      parentMethod = ()=>{
          console.log('被调用')
      }
    }
    <--子组件-->
    // component.ts
    import { Input } from '@angular/core';
    export class ChildComponent {
      @Input() inputProperty: ()=>{};
    }
    
  • 2,通过方法的方式

    <--父组件-->
    // .html
    <app-child (outputEvent)="parentMethod($event)"></app-child>
    // components.ts
    export class ParentComponent { 
        parentMethod(data: string) { 
            // 处理从子组件传递过来的数据 
            console.log('Received data from child component: ' + data); 
        } 
    }
    <--子组件-->
    // component.ts
    import { Output, EventEmitter } from '@angular/core'; 
    export class ChildComponent { 
    @Output() outputEvent = new EventEmitter<string>();
    triggerEvent() { 
        this.outputEvent.emit('some data'); } 
    }
    
  • *注意

    • 1,子组件使用父组件的时候,传递方法时,方法使用了服务;父子组件都需要注入
    • 2,同样也是单向数据流,子组件接收的值不要直接使用在template上。需要在子组件中定义一个变量接收后再使用。不然很可能出现内存溢出