Skip to content

7 Component Communication

7.1 Component Communication (Input to Child Components)

Parent to child:

app.component.html

<app-person name="sam" [age]="20"></app-person>

person.component.html

<p>person works!</p>
<p>{{ name }} {{ age }} </p>

person.component.ts

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-person',
  templateUrl: './person.component.html',
  styleUrls: ['./person.component.css']
})
export class PersonComponent implements OnInit {
  @Input("name") name: string ='';
  @Input("age") age: number = 0;

  constructor() { }

  ngOnInit(): void {
  }

}

Screenshot 2025-01-18 at 01.48.51

Screenshot 2025-01-18 at 01.49.01

PS: 在属性的外面加[]表示绑定动态值, 在组件内接受后是数字, 不加[]表示绑定普通值, 在组内接受后是字符串类型.

7.2 Component Communication (Output from Child Components)

Child to parent

需求: 在子组件中通过点击按钮将数据递给父组件

app (父) person(子)

Screenshot 2025-01-18 at 03.16.37

Screenshot 2025-01-18 at 03.16.44

person.component.ts:

import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-person',
  templateUrl: './person.component.html',
  styleUrls: ['./person.component.css']
})
export class PersonComponent implements OnInit { 

  @Input("name") name: string ='';
  @Input("age") age: number = 0;

  @Output() sendData = new EventEmitter()

  constructor() { }

  onClick() {
    this.sendData.emit("I am child component");
  }

  ngOnInit(): void {
  }

}

person.component.html

<p>person works!</p>
<p>{{ name }} {{ age }} </p>
<button (click)="onClick()" >transfer child to parent</button>

app.component.html

<app-person (sendData)="getData($event)"name="sam" [age]="20"></app-person>

app.component.ts

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


// 组件类 被@Component装饰器装饰
@Component({

  // 制定组件的使用方式, 当前问标记形式
  // app-root => <app-root></app-root> 

  selector: 'app-root', // 当前组件调用的时候你要以什么形式去调用
  templateUrl: './app.component.html', // 当前组件对应的模版是什么 组件模版文件路径
  styleUrls: ['./app.component.css'] // 当前组件对应的样式文件
})

// 导出一个类 
export class AppComponent {
  date = new Date();
  money = 110;
  title = 'angular-study';

  getData(event: string){
    alert(event);
  }
}