首页 > 其他 > 详细

Angular:组件之间的通信@Input、@Output和ViewChild

时间:2020-08-01 21:42:42      阅读:101      评论:0      收藏:0      [点我收藏+]

①父组件给子组件传值

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>

 

Angular:组件之间的通信@Input、@Output和ViewChild

原文:https://www.cnblogs.com/xinhej/p/13415659.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!