当前位置: 代码迷 >> 综合 >> Angular使用@Input和@Output实现父子组件互相传参(类似Vue的props和this.emit)
  详细解决方案

Angular使用@Input和@Output实现父子组件互相传参(类似Vue的props和this.emit)

热度:89   发布时间:2023-11-27 17:34:13.0

app.component.html 

<app-in-out [in]='"传输进入"' (out)="out($event)" ></app-in-out>

app.component.ts

import { Component } from '@angular/core';
@Component({selector: 'app-root',templateUrl: './app.component.html'
})
export class AppComponent {out($event: any) {alert($event);}
}

in-out/in-out.component.html

<h1>来自父组件的参数:{
   {in}}</h1> 
<button (click)="out.emit('向父组件传参')">向父组件传参</button>

in-out/in-out.component.ts

import { Component, Input, OnInit, Output, EventEmitter } from '@angular/core';@Component({selector: 'app-in-out',templateUrl: './in-out.component.html',styleUrls: ['./in-out.component.css']
})
export class InOutComponent implements OnInit {constructor() { }@Input() in: any = '';//从父组件传入参数进来@Output() out = new EventEmitter;//从子组件传出参数到父组件(采用事件的方式,类似Vue的emit)ngOnInit(): void {  }}

实现效果

  相关解决方案