Angular:组件之间的通信@Input、@Output和ViewChild
①父组件给子组件传值
1、父组件:
ts: export class HomeComponent implements OnInit { public hxTitle = '我是首页的头部'; constructor() { } ngOnInit(): void { } run(): void { alert('我是父组件的方法'); } } html: <app-header [hxTitle222]="hxTitle" [run]="run" [home]='this'></app-header>
2、子组件:
ts: import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.less'] }) export class HeaderComponent implements OnInit { @Input() hxTitle222: any; @Input() run: any; @Input() home: any; constructor() { } ngOnInit(): void { } getPRun(): void { this.run(); this.home.run(); console.log(this.home); } } html: <p>{{hxTitle222}}</p> <button (click)="getPRun()">我要执行父组件的方法</button>
②子组件给父组件传值
1、子组件:
ts: import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-newschild', templateUrl: './newschild.component.html', styleUrls: ['./newschild.component.less'] }) export class NewschildComponent implements OnInit { public hxMsg = '我是新闻孩子的信息'; @Output() hxMsg2 = new EventEmitter(); constructor() { } ngOnInit(): void { } run(): void { alert('我是新闻孩子的run方法'); } hxRun(): void { this.hxMsg2.emit(this.run); //广播方法 } } html: <button (click)="hxRun()">我要触发事件,并将值传给父组件</button>
2、父组件:
ts: import { Component, OnInit} from '@angular/core'; @Component({ selector: 'app-news', templateUrl: './news.component.html', styleUrls: ['./news.component.less'] }) export class NewsComponent implements OnInit { constructor() { } ngOnInit(): void { } getRun2(e): void { console.log(e); } } html: <app-newschild (hxMsg2)="getRun2($event)"></app-newschild>
③父组件拿到子组件中的属性或方法之@ViewChild
1、子组件:ts中定义一些属性和方法
2、父组件:
ts: import { Component, OnInit, ViewChild } from '@angular/core'; @Component({ selector: 'app-news', templateUrl: './news.component.html', styleUrls: ['./news.component.less'] }) export class NewsComponent implements OnInit { @ViewChild('newschild') newschild: any; constructor() { } ngOnInit(): void { } getMsg(): void { alert(this.newschild.hxMsg); //子组件中定义的属性 } getRun(): void { this.newschild.run(); //子组件中定义的方法 } } html: <button (click)="getMsg()">获取子组件的msg</button> <button (click)="getRun()">获取子组件的run方法</button> <app-newschild #newschild></app-newschild>