父组件给子组件传参

  1. //1.子组件通过属性接收父组件传递的参数
  2. //app.component.html
  3. <app-header [title]="name" ></app-header>
  1. //app.component.ts
  2. export class AppComponent {
  3. name:string='我是你爹';
  4. }
  1. //2.子组件引入Input模块
  2. //header.component.ts
  3. import { Component, OnInit ,Input} from '@angular/core';
  1. //3.子组件@input 接收父组件传过来的数据
  2. //header.ts
  3. export class HeaderComponent implements OnInit {
  4. @Input() title:string;
  5. ...
  6. }
  1. //4.子组件中使用父组件传递的数据
  2. //header.html
  3. <p>{{title}}</p>

子组件给父组件传参

  1. //1.在父组件创建方法
  2. //app.ts
  3. export class AppComponent {
  4. run(id:string){
  5. console.log(id)
  6. }
  7. }
  1. //app.html
  2. <app-header [title]="name" [run]="run" ></app-header>
  1. //2.子组件引入Input模块
  2. //header.component.ts
  3. import { Component, OnInit ,Input} from '@angular/core';
  1. //3.子组件@input传递参数
  2. //hearder.ts
  3. export class HeaderComponent implements OnInit {
  4. @Input() run:any;
  5. constructor() { }
  6. ngOnInit() {
  7. }
  8. handleClick(){
  9. this.run("1234")
  10. }
  11. }
  1. //header.html
  2. <button (click)="handleClick()">向父传参</button>

子组件通过@output传参

  1. //1.子组件引入模块Output,EventEmitter
  2. //header.ts
  3. import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
  1. //2.子组件中实例化EventEmitter
  2. //header.ts
  3. export class HeaderComponent implements OnInit {
  4. @Output() private outer=new EventEmitter<string>();
  5. ...
  6. }
  1. //3.子组件通过EventEmitter实例化的对象outer广播数据
  2. handleClick(){
  3. this.outer.emit("101001")
  4. }
  1. //header.html
  2. <button (click)="handleClick()">向父传参</button>
  1. //4.父组件接收参数
  2. //app.ts
  3. export class AppComponent {
  4. getId(id:string){
  5. console.log(id)
  6. }
  7. }
  1. //app.html
  2. <app-header (outer)="getId($event)"></app-header>