Angular的组件通信

丨@Input():父组件给子组件传值

//父.ts
public userInfo: any= "userInfo"
//父.html
<app-子 [userInfo]="userInfo"></app-子>
//子.ts
import { Component, OnInit, Input } from '@angular/core';
@Input() userInfo: any;
//子.html
{{userInfo}}

可以传递值或者方法


丨 @ViewChild():父组件调用子组件方法

//父.ts
import { Component, OnInit, ViewChild } from '@angular/core';
@ViewChild('子组件名称') 子组件名称:any
fun() {
    this.子组件名称.方法()
  }
//父.html
<app-子组件名称 #forms></app-子逐渐名称>

丨 @Output / EventEmitter:子组件调用父组件方法

//子.ts
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
 @Output() public outer = new EventEmitter
funChild(){
    this.outer.emit('我是子组件中的数据')
  }
//子.html
<button (click)="funChild()">点击</button>
//父.ts
funParent(data: any){
    alert(data)
  }
//父.html
<app-forms (outer)="funParent($event)"></app-forms>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容