打赏

angular 父子组件交互

1. 父子组件数据传递

1.1 父传子 @Input()

  <app-child [message]="message"></app-child>

子组件
import { Input } from '@angular/core';

  @Input()
  message?: string;

 1.2 子传父 @Output

父组件

  <app-child   (newItemEvent)="addItem($event)"></app-child>
addItem(data:string){ console.log('parent:',data) } 子组件 import { Output, EventEmitter } from '@angular/core';
@Output() newItemEvent = new EventEmitter<string>();
clickHandle(){ this.newItemEvent.emit('time' + new Date().getTime()) // 触发自定义事件 }

1.3 父调用子组件 ViewChild ,类似vue的ref

 <app-child [message]="message"  (newItemEvent)="addItem($event)" #child></app-child>


import {  ViewChild } from '@angular/core';

 @ViewChild('child') child:any;

 this.child.childFn(); // childFn 是子组件的方法

 

posted on 2024-03-24 13:17  jlyuan  阅读(13)  评论(0编辑  收藏  举报

导航